Skip to main content

adk_website/ui/
site.rs

1//! The site view (spec 3.5 §7.24, §8.2): status, releases and their page changes, KPIs with
2//! trends, jobs and their autonomy levels, signals, the wallet and held batches — and the
3//! owner's decisions on them.
4//!
5//! | Decision | Who | What happens |
6//! |---|---|---|
7//! | Promote a job | An owner (A-I13) | The kernel's ladder raises it one rung by the owner's decision, which answers the job's waiting promotion request; the harness grants the standing rules the new level needs |
8//! | Lower a job | An owner | The ladder lowers it one rung; the standing rules it no longer warrants are revoked |
9//! | Release or discard a held item | An owner, never the change's proposer (A-I23, A-I25) | The update engine publishes it at once, or drops it |
10//! | Release or discard a held feed delivery | An owner (A-I27) | The engine applies it whole, or drops it whole |
11//! | Acknowledge an alarm | Anyone with a role | The alarm stops repeating |
12
13use std::collections::BTreeMap;
14
15use adk_core::Result;
16use adk_core::principal::SubjectRef;
17use adk_harness::website::{LadderCompiler, apply_demotion, promote_job};
18use adk_kernel::charter::{KpiPhase, OwnerDecision, PromotionEligibility, SignalFilter};
19use adk_payments::wallet::{HoldReason as WalletHold, PaymentQuery, PaymentState};
20use adk_site::feed::bounds::BoundBreak;
21use adk_site::pipeline::PageChange;
22use adk_site::release::manifest_path;
23use adk_site::updates::{Decision, HoldReason};
24use awp_types::{
25    AutonomyLevel, ContentId, Direction, FileEntry, ReleaseManifest, ReleaseSource, Role,
26    SignalKind, SpendCategory, Urgency,
27};
28use chrono::{DateTime, Datelike, Utc};
29use schemars::JsonSchema;
30use serde::{Deserialize, Serialize};
31
32use super::words::{self, major, money};
33use super::{Pill, Tone, WebsiteDesk, invalid, kernel, not_found, site, unavailable};
34use crate::kinds::template;
35use crate::team::SiteTeam;
36
37/// How many releases the view lists.
38const RELEASES: u64 = 8;
39
40/// The site's status (spec 3.5 §7.5).
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
42#[serde(rename_all = "camelCase")]
43pub struct StatusView {
44    /// The state, as a pill.
45    pub state: Pill,
46    /// Since when.
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub since: Option<DateTime<Utc>>,
49    /// Why, in words.
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub reason: Option<String>,
52}
53
54/// A page a release changed (spec 3.3 §7.5).
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
56#[serde(rename_all = "camelCase")]
57pub struct PageLine {
58    /// The page.
59    pub path: String,
60    /// How it changed.
61    pub change: Pill,
62}
63
64/// One signed release (spec 3.5 §7.7).
65#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
66#[serde(rename_all = "camelCase")]
67pub struct ReleaseLine {
68    /// Its number.
69    pub seq: u64,
70    /// When it was built.
71    pub at: DateTime<Utc>,
72    /// What made it, in words.
73    pub source: String,
74    /// The pages it changed.
75    pub pages: Vec<PageLine>,
76    /// How many other files it changed.
77    pub other_files: usize,
78}
79
80/// One KPI this week (spec 3.5 §7.11, §7.24).
81#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
82#[serde(rename_all = "camelCase")]
83pub struct KpiCard {
84    /// The KPI.
85    pub id: String,
86    /// Its name.
87    pub name: String,
88    /// This week.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub this_week: Option<String>,
91    /// The week before.
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    pub last_week: Option<String>,
94    /// Its baseline.
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub baseline: Option<String>,
97    /// Its target, the owner's.
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    pub target: Option<String>,
100    /// The trend, in its direction: up is better.
101    pub trend: Pill,
102    /// "Measuring until 8 Nov" or "Tracking".
103    pub phase: String,
104}
105
106/// One job and its level (spec 3.5 §7.11, §7.20).
107#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
108#[serde(rename_all = "camelCase")]
109pub struct JobLine {
110    /// The job.
111    pub id: String,
112    /// What it is.
113    pub title: String,
114    /// Its area.
115    pub area: String,
116    /// The agent that does it.
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    pub agent: Option<String>,
119    /// How much it does alone.
120    pub level: String,
121    /// Since when.
122    pub since: DateTime<Utc>,
123    /// Its record towards a promotion.
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub record: Option<String>,
126    /// Whether it has earned the offer of a promotion.
127    pub offered: bool,
128    /// The level a promotion would give it.
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    pub next: Option<String>,
131    /// Whether the viewer may raise it.
132    pub can_promote: bool,
133    /// Whether the viewer may lower it.
134    pub can_lower: bool,
135}
136
137/// One signal from the public side, typed and screened (spec 3.5 §7.10).
138#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
139#[serde(rename_all = "camelCase")]
140pub struct SignalLine {
141    /// What it is.
142    pub text: String,
143    /// How many arrived.
144    pub count: u32,
145    /// The latest.
146    pub last_at: DateTime<Utc>,
147}
148
149/// Signals waiting in the back office.
150#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
151#[serde(rename_all = "camelCase")]
152pub struct SignalsView {
153    /// How many are open.
154    pub open: usize,
155    /// The latest open ones.
156    pub lines: Vec<SignalLine>,
157}
158
159/// A spend category against its cap.
160#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
161#[serde(rename_all = "camelCase")]
162pub struct CategoryLine {
163    /// The category.
164    pub name: String,
165    /// Spent this month.
166    pub spent: String,
167    /// Its cap.
168    pub cap: String,
169    /// Spent as a share of the cap, in percent from 0 to 100.
170    pub percent: u32,
171    /// Why it is paused, when it is.
172    #[serde(default, skip_serializing_if = "Option::is_none")]
173    pub paused: Option<String>,
174}
175
176/// A payment held for the owner (spec 3.5 §7.14).
177#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
178#[serde(rename_all = "camelCase")]
179pub struct HeldPayment {
180    /// What it is for.
181    pub description: String,
182    /// How much.
183    pub amount: String,
184    /// Why it waits.
185    pub why: String,
186}
187
188/// The wallet (spec 3.5 §7.14).
189#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
190#[serde(rename_all = "camelCase")]
191pub struct WalletView {
192    /// What is available.
193    pub balance: String,
194    /// Spent this month.
195    pub spent: String,
196    /// The month's caps together.
197    pub budget: String,
198    /// Each category.
199    pub categories: Vec<CategoryLine>,
200    /// Payments held for the owner.
201    pub held: Vec<HeldPayment>,
202}
203
204/// An item held alone (spec 3.5 §7.8.3).
205#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
206#[serde(rename_all = "camelCase")]
207pub struct HeldItemLine {
208    /// The item.
209    pub id: String,
210    /// Its title.
211    pub title: String,
212    /// Why it waits.
213    pub reason: String,
214    /// The batch it came in.
215    pub batch: u64,
216    /// When it was held.
217    pub held_at: DateTime<Utc>,
218}
219
220/// A feed delivery held whole (spec 3.5 A-I27).
221#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
222#[serde(rename_all = "camelCase")]
223pub struct HeldDeliveryLine {
224    /// The delivery.
225    pub delivery: u64,
226    /// The feed.
227    pub feed: String,
228    /// The bounds it broke.
229    pub breaks: Vec<String>,
230    /// What it would change.
231    pub would: Vec<String>,
232    /// When it arrived.
233    pub received_at: DateTime<Utc>,
234}
235
236/// One recent batch.
237#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
238#[serde(rename_all = "camelCase")]
239pub struct BatchLine {
240    /// The batch.
241    pub batch: u64,
242    /// When it closed.
243    pub closed_at: DateTime<Utc>,
244    /// One line.
245    pub text: String,
246}
247
248/// Held batches (spec 3.5 §7.8.3).
249#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
250#[serde(rename_all = "camelCase")]
251pub struct HeldView {
252    /// Items held alone.
253    pub items: Vec<HeldItemLine>,
254    /// Deliveries held whole.
255    pub deliveries: Vec<HeldDeliveryLine>,
256    /// The latest batches.
257    pub batches: Vec<BatchLine>,
258}
259
260/// An open alarm (spec 3.5 §7.21).
261#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
262#[serde(rename_all = "camelCase")]
263pub struct AlarmLine {
264    /// The alarm.
265    pub id: String,
266    /// Its urgency.
267    pub urgency: Pill,
268    /// What happened.
269    pub text: String,
270    /// When.
271    pub raised_at: DateTime<Utc>,
272    /// Whether it repeats until a person acknowledges it: an urgent alarm.
273    pub can_acknowledge: bool,
274}
275
276/// The site as every surface shows it (spec 3.5 §7.24).
277#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
278#[serde(rename_all = "camelCase")]
279pub struct SiteViewModel {
280    /// The site's name.
281    pub name: String,
282    /// Its public address.
283    pub origin: String,
284    /// Whether it is live.
285    pub launched: bool,
286    /// Its status.
287    pub status: StatusView,
288    /// The latest releases, newest first.
289    pub releases: Vec<ReleaseLine>,
290    /// This week's KPIs.
291    pub kpis: Vec<KpiCard>,
292    /// The jobs and their levels.
293    pub jobs: Vec<JobLine>,
294    /// Signals from the public side.
295    pub signals: SignalsView,
296    /// The wallet, when the site has one.
297    #[serde(default, skip_serializing_if = "Option::is_none")]
298    pub wallet: Option<WalletView>,
299    /// Held batches.
300    pub held: HeldView,
301    /// Open alarms.
302    pub alarms: Vec<AlarmLine>,
303    /// Whether the viewer decides as an owner.
304    pub owner: bool,
305}
306
307/// An owner's decision on the site view.
308#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
309#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
310pub enum SiteCommand {
311    /// Raise a job one rung (A-I13).
312    Promote {
313        /// The job.
314        job: String,
315    },
316    /// Lower a job one rung.
317    Lower {
318        /// The job.
319        job: String,
320        /// Why.
321        reason: String,
322    },
323    /// Release or discard an item held alone.
324    Item {
325        /// The item.
326        id: String,
327        /// `release` or `discard`.
328        decision: HeldDecision,
329    },
330    /// Release or discard a delivery held whole (A-I27).
331    Delivery {
332        /// The delivery.
333        delivery: u64,
334        /// `release` or `discard`.
335        decision: HeldDecision,
336    },
337    /// Acknowledge an alarm.
338    Acknowledge {
339        /// The alarm.
340        alarm: String,
341    },
342}
343
344/// The owner's decision on something held.
345#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
346#[serde(rename_all = "camelCase")]
347pub enum HeldDecision {
348    /// Publish it.
349    Release,
350    /// Drop it.
351    Discard,
352}
353
354/// What a site decision did.
355#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
356#[serde(rename_all = "camelCase")]
357pub struct SiteOutcome {
358    /// The view after it.
359    pub view: SiteViewModel,
360    /// One line on what happened.
361    #[serde(default, skip_serializing_if = "Option::is_none")]
362    pub note: Option<String>,
363}
364
365pub(crate) fn source_words(source: &ReleaseSource) -> String {
366    match source {
367        ReleaseSource::Onboarding => "The first release".into(),
368        ReleaseSource::Migration => "Moved from the old site".into(),
369        ReleaseSource::Rollback { to_seq } => format!("Rolled back to release {to_seq}"),
370        ReleaseSource::Edit { job, .. } => match job.as_str() {
371            "web-editor" => "An edit in the web editor".into(),
372            "correction" => "A correction".into(),
373            "withdrawal" => "A withdrawal".into(),
374            "revert" => "One item undone".into(),
375            "onboarding" => "The launch".into(),
376            other => crate::jobs::job(other).map_or_else(
377                || format!("An edit by {}", other.replace('-', " ")),
378                |spec| format!("{} job", spec.title),
379            ),
380        },
381        _ => "A release".into(),
382    }
383}
384
385fn hold_words(reason: &HoldReason) -> String {
386    match reason {
387        HoldReason::PriceRule { allowed_pct } => {
388            format!("The price moves more than the {allowed_pct}% your price rule allows")
389        }
390        HoldReason::NewItem => "A new item waits for its approval".into(),
391        HoldReason::FastTier { findings } => format!(
392            "It failed a check: {}",
393            findings.first().map_or("see the batch", |f| f.message.as_str())
394        ),
395        _ => "It waits for you".into(),
396    }
397}
398
399/// "item" or "items", for `n` of them.
400fn items(n: usize) -> &'static str {
401    if n == 1 { "item" } else { "items" }
402}
403
404fn break_words(bound: &BoundBreak) -> String {
405    match bound {
406        BoundBreak::ChangeFraction { changed, collection, max } => format!(
407            "It changes {changed} of {collection} {}; at most {:.0}% may change at once",
408            items(*collection),
409            max * 100.0
410        ),
411        BoundBreak::Field { field, key, .. } => format!(
412            "{} has a value outside its allowed range{}",
413            field.as_deref().map_or("A field".to_string(), |f| format!("The {f}")),
414            key.as_deref().map(|k| format!(" (record {k})")).unwrap_or_default()
415        ),
416        BoundBreak::Rate { records, .. } => {
417            format!("{records} records in a minute is faster than allowed")
418        }
419        _ => "It breaks a bound".into(),
420    }
421}
422
423fn signal_words(kind: &SignalKind) -> String {
424    match kind {
425        SignalKind::LeadCaptured { source, .. } => format!("A new lead, from {}", source.as_str()),
426        SignalKind::ContentGap { topic, question_count, .. } => {
427            format!(
428                "Visitors asked about \u{201c}{}\u{201d} ({question_count} times)",
429                topic.as_str()
430            )
431        }
432        SignalKind::VisitorIntent { capability, .. } => {
433            format!("Someone tried {}", capability.replace('_', " "))
434        }
435        SignalKind::SupportEscalation { reason, .. } => {
436            format!("Someone needs help: {}", reason.0.replace('_', " "))
437        }
438        SignalKind::ReviewSeen { platform, rating, .. } => {
439            format!("A {rating}-star review on {platform}")
440        }
441        SignalKind::InboundMessage { channel, .. } => format!("A message on {}", channel.as_str()),
442        SignalKind::AgentInteraction { capability, .. } => {
443            format!("An agent used {}", capability.replace('_', " "))
444        }
445        _ => "Something on the public side".into(),
446    }
447}
448
449/// The page files of a release that changed, against the release before it.
450fn page_changes(
451    before: &BTreeMap<String, FileEntry>,
452    after: &BTreeMap<String, FileEntry>,
453) -> (Vec<PageLine>, usize) {
454    let mut pages = Vec::new();
455    let mut other = 0;
456    for (path, entry) in after {
457        let change = match before.get(path) {
458            None => PageChange::Added,
459            Some(old) if old != entry => PageChange::Changed,
460            Some(_) => continue,
461        };
462        if path.ends_with(".html") {
463            pages.push(PageLine { path: path.clone(), change: words::page_change(change) });
464        } else {
465            other += 1;
466        }
467    }
468    for path in before.keys().filter(|p| !after.contains_key(*p)) {
469        if path.ends_with(".html") {
470            pages.push(PageLine {
471                path: path.clone(),
472                change: words::page_change(PageChange::Removed),
473            });
474        } else {
475            other += 1;
476        }
477    }
478    (pages, other)
479}
480
481impl WebsiteDesk {
482    /// The full file set of release `seq`, from the manifests the host serves.
483    async fn files_of(
484        &self,
485        seq: u64,
486        cache: &mut BTreeMap<u64, (ReleaseManifest, BTreeMap<String, FileEntry>)>,
487    ) -> Result<Option<(ReleaseManifest, BTreeMap<String, FileEntry>)>> {
488        if let Some(found) = cache.get(&seq) {
489            return Ok(Some(found.clone()));
490        }
491        let runtime = self.runtime().await;
492        let mut chain: Vec<ReleaseManifest> = Vec::new();
493        let mut base_files = BTreeMap::new();
494        let mut at = seq;
495        loop {
496            if let Some((_, files)) = cache.get(&at) {
497                base_files = files.clone();
498                break;
499            }
500            let Some(bytes) = runtime.host().fetch(&manifest_path(at)).await.map_err(site)? else {
501                return Ok(None);
502            };
503            let manifest: ReleaseManifest = serde_json::from_slice(&bytes).map_err(|e| {
504                invalid("website.site.manifest", format!("release {at}'s manifest: {e}"))
505            })?;
506            let base = manifest.base;
507            chain.push(manifest);
508            match base {
509                Some(base) => at = base,
510                None => break,
511            }
512        }
513        let mut files = base_files;
514        for manifest in chain.iter().rev() {
515            files = manifest.apply_to(&files);
516            cache.insert(manifest.seq, (manifest.clone(), files.clone()));
517        }
518        Ok(cache.get(&seq).cloned())
519    }
520
521    async fn releases(&self) -> Result<Vec<ReleaseLine>> {
522        let runtime = self.runtime().await;
523        let Some(latest) = runtime.pipeline().previous().await.map(|p| p.manifest.seq) else {
524            return Ok(Vec::new());
525        };
526        let mut cache = BTreeMap::new();
527        let mut lines = Vec::new();
528        let first = latest.saturating_sub(RELEASES - 1).max(1);
529        for seq in (first..=latest).rev() {
530            let Some((manifest, files)) = self.files_of(seq, &mut cache).await? else { continue };
531            let before = if seq > 1 {
532                self.files_of(seq - 1, &mut cache)
533                    .await?
534                    .map(|(_, files)| files)
535                    .unwrap_or_default()
536            } else {
537                BTreeMap::new()
538            };
539            let (pages, other_files) = page_changes(&before, &files);
540            lines.push(ReleaseLine {
541                seq,
542                at: manifest.created_at,
543                source: source_words(&manifest.source),
544                pages,
545                other_files,
546            });
547        }
548        Ok(lines)
549    }
550
551    async fn compiler(&self) -> Result<Option<(LadderCompiler, awp_types::Charter)>> {
552        let Some(charters) = &self.inner.charters else { return Ok(None) };
553        let Some(current) = charters.current(self.inner.site.id).await.map_err(kernel)? else {
554            return Ok(None);
555        };
556        let template = template(current.charter.kind);
557        let team = SiteTeam::new(self.inner.site.clone(), &template);
558        let jobs = template.jobs();
559        let compiler = LadderCompiler::new(self.inner.site.clone())
560            .with_charter(&current.charter, crate::jobs::bindings(&team, &jobs));
561        Ok(Some((compiler, current.charter)))
562    }
563
564    /// The site view for `person` (spec 3.5 §7.24). Anyone holding a role in the charter
565    /// reads it.
566    ///
567    /// # Errors
568    ///
569    /// `Forbidden` for a person with no role; the stores' errors.
570    pub async fn site_view(&self, person: &str) -> Result<SiteViewModel> {
571        let roles = self.roles(person).await?;
572        if roles.is_empty() {
573            return Err(super::forbidden(
574                "website.ui.not_allowed",
575                format!("{person} holds no role in this site's charter"),
576            ));
577        }
578        let owner = roles.contains(&Role::Owner);
579        let site_id = self.inner.site.id;
580        let now = self.now();
581        let today = now.date_naive();
582        let monday =
583            today - chrono::Duration::days(i64::from(today.weekday().num_days_from_monday()));
584
585        let status = match &self.inner.status {
586            Some(status) => status.get(site_id).await?,
587            None => None,
588        };
589        let status = match status {
590            Some(record) => StatusView {
591                state: words::site_state(record.state),
592                since: Some(record.since),
593                reason: Some(sentence(&record.reason)),
594            },
595            None => StatusView {
596                state: Pill::new("Not live yet", Tone::Neutral),
597                since: None,
598                reason: None,
599            },
600        };
601        let releases = self.releases().await?;
602        let charter = match &self.inner.charters {
603            Some(charters) => charters.current(site_id).await.map_err(kernel)?.map(|c| c.charter),
604            None => None,
605        };
606
607        let mut kpis = Vec::new();
608        if let Some(tracker) = &self.inner.tracker {
609            for review in tracker.review(monday).await.map_err(kernel)? {
610                let direction = charter
611                    .as_ref()
612                    .and_then(|c| c.kpis.iter().find(|k| k.id == review.kpi).map(|k| k.direction));
613                let trend = match (review.week, review.previous_week) {
614                    (Some(week), Some(previous)) if (week - previous).abs() < f64::EPSILON => {
615                        Pill::new("Same", Tone::Neutral)
616                    }
617                    (Some(week), Some(previous)) => {
618                        let better =
619                            matches!(direction, Some(Direction::Down)) != (week > previous);
620                        if better {
621                            Pill::new("Better", Tone::Good)
622                        } else {
623                            Pill::new("Worse", Tone::Bad)
624                        }
625                    }
626                    _ => Pill::new("New", Tone::Neutral),
627                };
628                kpis.push(KpiCard {
629                    id: review.kpi.clone(),
630                    name: review.name.clone(),
631                    this_week: review.week.map(words::number),
632                    last_week: review.previous_week.map(words::number),
633                    baseline: review.baseline.map(words::number),
634                    target: review.target.map(words::number),
635                    trend,
636                    phase: match &review.phase {
637                        KpiPhase::MeasureOnly { until } => {
638                            format!("Finding its baseline until {}", until.format("%-d %b"))
639                        }
640                        _ => "Tracking".into(),
641                    },
642                });
643            }
644        }
645
646        let mut jobs = Vec::new();
647        if let Some(ladder) = &self.inner.ladder {
648            let records = ladder.store().list(site_id).await.map_err(kernel)?;
649            let mut offers: BTreeMap<String, PromotionEligibility> = BTreeMap::new();
650            for record in &records {
651                offers.insert(
652                    record.job.clone(),
653                    ladder.eligibility(site_id, &record.job).await.map_err(kernel)?,
654                );
655            }
656            let team =
657                charter.as_ref().map(|c| SiteTeam::new(self.inner.site.clone(), &template(c.kind)));
658            for record in records {
659                let spec = crate::jobs::job(&record.job);
660                let offer = offers.get(&record.job);
661                let next = offer.and_then(|o| o.next);
662                jobs.push(JobLine {
663                    title: spec
664                        .map_or_else(|| record.job.replace('-', " "), |s| s.title.to_string()),
665                    area: record.area.as_deref().map_or("Other", words::area).into(),
666                    agent: match (spec, &team) {
667                        (Some(spec), Some(team)) => {
668                            spec.ladder_agent(team).map(|a| words::agent(a).to_string())
669                        }
670                        _ => None,
671                    },
672                    level: words::level(record.level).into(),
673                    since: record.since,
674                    record: offer.filter(|o| o.streak > 0).map(|o| {
675                        format!(
676                            "{} of {} approvals in a row unchanged",
677                            o.streak.min(o.needed),
678                            o.needed
679                        )
680                    }),
681                    offered: offer.is_some_and(|o| o.eligible),
682                    next: next.map(|level| words::level(level).to_string()),
683                    // Autonomy is earned (D-7): the owner promotes a job the record offers.
684                    can_promote: owner
685                        && next.is_some()
686                        && offer.is_some_and(|o| o.eligible)
687                        && self.inner.rules.is_some(),
688                    can_lower: owner && record.level != AutonomyLevel::Observe,
689                    id: record.job,
690                });
691            }
692            jobs.sort_by(|a, b| {
693                (b.offered, &a.area, &a.title).cmp(&(a.offered, &b.area, &b.title))
694            });
695        }
696
697        let signals = match &self.inner.signals {
698            Some((store, partition)) => {
699                let records = store
700                    .list(&SignalFilter::default().partition(partition.clone()).open(true))
701                    .await
702                    .map_err(kernel)?;
703                let mut lines: Vec<SignalLine> = records
704                    .iter()
705                    .map(|record| SignalLine {
706                        text: signal_words(&record.signal.kind),
707                        count: record.count,
708                        last_at: record.last_at,
709                    })
710                    .collect();
711                lines.sort_by_key(|line| std::cmp::Reverse(line.last_at));
712                lines.truncate(8);
713                SignalsView { open: records.len(), lines }
714            }
715            None => SignalsView { open: 0, lines: Vec::new() },
716        };
717
718        let wallet = match &self.inner.wallet {
719            Some(parts) => {
720                let policy = parts.wallet.policy();
721                let currency = policy.currency.clone();
722                let month = today
723                    .with_day(1)
724                    .and_then(|day| day.and_hms_opt(0, 0, 0))
725                    .map_or(now, |start| start.and_utc());
726                let read = |metric: String| {
727                    let kpi = parts.kpi.clone();
728                    async move {
729                        kpi.0.read(site_id, &metric, month, now).await.ok().flatten().unwrap_or(0.0)
730                    }
731                };
732                let pauses = parts.store.pauses(parts.wallet.id()).await.unwrap_or_default();
733                let mut categories = Vec::new();
734                let mut budget = 0u64;
735                for (category, mandate) in &policy.categories {
736                    budget += mandate.cap_per_period;
737                    let spent = read(format!("spend.{}", category_key(*category))).await;
738                    let cap_major = mandate.cap_per_period as f64
739                        / 10f64.powi(words::minor_exponent(&currency));
740                    categories.push(CategoryLine {
741                        name: words::category(*category).into(),
742                        spent: major(spent, &currency),
743                        cap: money(mandate.cap_per_period, &currency),
744                        percent: if cap_major > 0.0 {
745                            ((spent / cap_major).clamp(0.0, 1.0) * 100.0).round() as u32
746                        } else {
747                            0
748                        },
749                        paused: pauses
750                            .iter()
751                            .find(|p| p.category == *category)
752                            .map(|p| p.reason.clone()),
753                    });
754                }
755                let held = parts
756                    .store
757                    .list(&PaymentQuery::new(parts.wallet.id()).state(PaymentState::Held))
758                    .await
759                    .unwrap_or_default()
760                    .into_iter()
761                    .map(|payment| HeldPayment {
762                        description: payment.description.clone(),
763                        amount: money(payment.amount, &payment.currency),
764                        why: match &payment.hold {
765                            Some(WalletHold::OverPaymentLimit { max_per_payment, .. }) => format!(
766                                "Over the {} limit for one payment",
767                                money(*max_per_payment, &payment.currency)
768                            ),
769                            Some(WalletHold::OverCategoryCap { cap, spent, .. }) => format!(
770                                "It would take the month past its {} cap ({} spent)",
771                                money(*cap, &payment.currency),
772                                money(*spent, &payment.currency)
773                            ),
774                            _ => "Over a limit you set".into(),
775                        },
776                    })
777                    .collect();
778                Some(WalletView {
779                    balance: money(parts.wallet.balance().await.unwrap_or(0), &currency),
780                    spent: major(read("spend".into()).await, &currency),
781                    budget: money(budget, &currency),
782                    categories,
783                    held,
784                })
785            }
786            None => None,
787        };
788
789        let held = match &self.inner.updates {
790            Some(engine) => HeldView {
791                items: engine
792                    .held_items()
793                    .await
794                    .into_iter()
795                    .map(|held| HeldItemLine {
796                        id: held.update.item.id.0.clone(),
797                        title: held
798                            .update
799                            .item
800                            .fields
801                            .get("title")
802                            .and_then(|v| v.as_str())
803                            .map_or_else(|| held.update.item.slug.clone(), str::to_string),
804                        reason: hold_words(&held.reason),
805                        batch: held.batch,
806                        held_at: held.held_at,
807                    })
808                    .collect(),
809                deliveries: engine
810                    .held_deliveries()
811                    .await
812                    .into_iter()
813                    .map(|held| {
814                        let summary = &held.report.summary;
815                        let mut would = vec![format!(
816                            "Change {} of {} {} ({:.0}%)",
817                            summary.items_changed,
818                            summary.collection,
819                            items(summary.collection),
820                            summary.fraction * 100.0
821                        )];
822                        if let Some(prices) = &summary.prices {
823                            would.push(if prices.changed == 1 {
824                                format!("1 price changes, by {:.0}%", prices.largest_change_pct)
825                            } else {
826                                format!(
827                                    "{} prices change, the largest by {:.0}%",
828                                    prices.changed, prices.largest_change_pct
829                                )
830                            });
831                        }
832                        HeldDeliveryLine {
833                            delivery: held.delivery,
834                            feed: held.feed.clone(),
835                            breaks: held.report.breaks.iter().map(break_words).collect(),
836                            would,
837                            received_at: held.received_at,
838                        }
839                    })
840                    .collect(),
841                batches: engine
842                    .batches()
843                    .await
844                    .into_iter()
845                    .rev()
846                    .take(5)
847                    .map(|batch| BatchLine {
848                        batch: batch.batch,
849                        closed_at: batch.closed_at,
850                        text: match (&batch.refused, batch.release_seq) {
851                            (Some(reason), _) => format!("Refused whole: {reason}"),
852                            (None, Some(seq)) => format!(
853                                "{} item{} live in release {seq}{}",
854                                batch.published.len(),
855                                if batch.published.len() == 1 { "" } else { "s" },
856                                if batch.held.is_empty() {
857                                    String::new()
858                                } else {
859                                    format!("; {} held", batch.held.len())
860                                }
861                            ),
862                            (None, None) => format!("Nothing published; {} held", batch.held.len()),
863                        },
864                    })
865                    .collect(),
866            },
867            None => HeldView { items: Vec::new(), deliveries: Vec::new(), batches: Vec::new() },
868        };
869
870        let alarms = match &self.inner.alarms {
871            Some(router) => {
872                let open = router.open().await;
873                let recent = router.raised_since(now - chrono::Duration::days(1)).await;
874                let open_ids: Vec<String> = open.iter().map(|alarm| alarm.id.clone()).collect();
875                let mut lines: Vec<AlarmLine> = open
876                    .into_iter()
877                    .map(|alarm| (alarm, true))
878                    .chain(
879                        recent
880                            .into_iter()
881                            .filter(|alarm| !open_ids.contains(&alarm.id))
882                            .filter(|alarm| alarm.urgency == Urgency::P2)
883                            .map(|alarm| (alarm, false)),
884                    )
885                    .map(|(alarm, open)| AlarmLine {
886                        urgency: match alarm.urgency {
887                            Urgency::P1 => Pill::new("Urgent", Tone::Bad),
888                            Urgency::P2 => Pill::new("Within the hour", Tone::Waiting),
889                            _ => Pill::new("For the review", Tone::Neutral),
890                        },
891                        text: alarm.summary.clone(),
892                        raised_at: alarm.raised_at,
893                        id: alarm.id,
894                        can_acknowledge: open,
895                    })
896                    .collect();
897                lines.sort_by_key(|line| std::cmp::Reverse(line.raised_at));
898                lines
899            }
900            None => Vec::new(),
901        };
902
903        Ok(SiteViewModel {
904            name: self.site_name().await,
905            origin: self.inner.site.origin.clone(),
906            launched: !releases.is_empty(),
907            status,
908            releases,
909            kpis,
910            jobs,
911            signals,
912            wallet,
913            held,
914            alarms,
915            owner,
916        })
917    }
918
919    /// Carries out an owner's `command` on the site view (spec 3.5 §7.11, §7.8.3, A-I13,
920    /// A-I23, A-I27).
921    ///
922    /// # Errors
923    ///
924    /// `Forbidden` for a person who is not an owner; the ladder's, the rule store's and the
925    /// update engine's errors.
926    pub async fn site_command(&self, person: &str, command: SiteCommand) -> Result<SiteOutcome> {
927        let note = match command {
928            SiteCommand::Promote { job } => {
929                self.require(person, &[Role::Owner], "Promoting a job").await?;
930                let ladder =
931                    self.inner.ladder.as_ref().ok_or_else(|| unavailable("The autonomy ladder"))?;
932                let rules = self
933                    .inner
934                    .rules
935                    .clone()
936                    .ok_or_else(|| unavailable("The standing-rule store"))?;
937                let (compiler, _) = self.compiler().await?.ok_or_else(|| {
938                    invalid("website.site.no_charter", "jobs are promoted under a signed charter")
939                })?;
940                // Autonomy is earned (D-7, §7.11): the owner accepts an offer the job's record
941                // made.
942                let eligibility =
943                    ladder.eligibility(self.inner.site.id, &job).await.map_err(kernel)?;
944                if !eligibility.eligible {
945                    return Err(invalid(
946                        "website.site.not_earned",
947                        format!(
948                            "{job} has {} of the {} unchanged approvals in a row a promotion needs",
949                            eligibility.streak.min(eligibility.needed),
950                            eligibility.needed
951                        ),
952                    ));
953                }
954                // The owner's decision answers the job's waiting promotion request, the one the
955                // kernel's inbox and chat cards show, and names it (#1280).
956                let runtime = self.runtime().await;
957                let waiting = runtime
958                    .promotion_requests()
959                    .await
960                    .into_iter()
961                    .find(|request| request.job == job);
962                let decision_id = match waiting {
963                    Some(request) => {
964                        runtime
965                            .approvals()
966                            .approve(&request.id, request.version, &SubjectRef::human(person))
967                            .await?;
968                        request.id
969                    }
970                    None => self.next_id("promote"),
971                };
972                let decision =
973                    OwnerDecision::new(decision_id, SubjectRef::human(person), self.now());
974                let promotion =
975                    promote_job(ladder, &compiler, rules.as_ref(), &job, &decision, person).await?;
976                crate::observability::record_autonomy_change(&job, None, promotion.job.level);
977                format!(
978                    "{} now works at \u{201c}{}\u{201d}, by your decision.",
979                    crate::jobs::job(&job).map_or(job.as_str(), |s| s.title),
980                    words::level(promotion.job.level)
981                )
982            }
983            SiteCommand::Lower { job, reason } => {
984                self.require(person, &[Role::Owner], "Lowering a job").await?;
985                let ladder =
986                    self.inner.ladder.as_ref().ok_or_else(|| unavailable("The autonomy ladder"))?;
987                let reason = if reason.trim().is_empty() {
988                    "the owner lowered it".to_string()
989                } else {
990                    reason.trim().to_string()
991                };
992                let lowered = ladder
993                    .lower(self.inner.site.id, &job, &format!("{person}: {reason}"))
994                    .await
995                    .map_err(kernel)?
996                    .ok_or_else(|| invalid("website.site.bottom", "the job only looks already"))?;
997                if let (Some(rules), Some((compiler, _))) =
998                    (&self.inner.rules, self.compiler().await?)
999                {
1000                    apply_demotion(&compiler, rules.as_ref(), &job, lowered.level).await?;
1001                }
1002                format!(
1003                    "{} now works at \u{201c}{}\u{201d}.",
1004                    crate::jobs::job(&job).map_or(job.as_str(), |s| s.title),
1005                    words::level(lowered.level)
1006                )
1007            }
1008            SiteCommand::Item { id, decision } => {
1009                self.require(person, &[Role::Owner], "Deciding a held item").await?;
1010                let engine =
1011                    self.inner.updates.as_ref().ok_or_else(|| unavailable("The update engine"))?;
1012                let records = engine
1013                    .decide_item(&ContentId(id), decision.into(), person)
1014                    .await
1015                    .map_err(site)?;
1016                match decision {
1017                    HeldDecision::Discard => "Discarded; nothing from it is published.".into(),
1018                    HeldDecision::Release => match records.iter().find_map(|r| r.release_seq) {
1019                        Some(seq) => format!("Released in release {seq}."),
1020                        None => "Released; it goes out with the next batch.".into(),
1021                    },
1022                }
1023            }
1024            SiteCommand::Delivery { delivery, decision } => {
1025                self.require(person, &[Role::Owner], "Deciding a held delivery").await?;
1026                let engine =
1027                    self.inner.updates.as_ref().ok_or_else(|| unavailable("The update engine"))?;
1028                let outcome = engine
1029                    .decide_delivery(delivery, decision.into(), person)
1030                    .await
1031                    .map_err(site)?;
1032                match decision {
1033                    HeldDecision::Discard => "The whole delivery is discarded.".into(),
1034                    HeldDecision::Release => {
1035                        format!("Applied: {} changes queued.", outcome.queued + outcome.live)
1036                    }
1037                }
1038            }
1039            SiteCommand::Acknowledge { alarm } => {
1040                if self.roles(person).await?.is_empty() {
1041                    return Err(super::forbidden(
1042                        "website.ui.not_allowed",
1043                        "only people with a role acknowledge alarms",
1044                    ));
1045                }
1046                let router = self.inner.alarms.as_ref().ok_or_else(|| unavailable("Alarms"))?;
1047                router.acknowledge(&alarm, &SubjectRef::human(person)).await.map_err(|_| {
1048                    not_found("website.site.alarm", format!("no open alarm '{alarm}'"))
1049                })?;
1050                "Acknowledged.".into()
1051            }
1052        };
1053        Ok(SiteOutcome { view: self.site_view(person).await?, note: Some(note) })
1054    }
1055}
1056
1057impl From<HeldDecision> for Decision {
1058    fn from(decision: HeldDecision) -> Self {
1059        match decision {
1060            HeldDecision::Release => Decision::Release,
1061            HeldDecision::Discard => Decision::Discard,
1062        }
1063    }
1064}
1065
1066fn category_key(category: SpendCategory) -> &'static str {
1067    match category {
1068        SpendCategory::Hosting => "hosting",
1069        SpendCategory::Models => "models",
1070        SpendCategory::Advertising => "advertising",
1071        SpendCategory::Domains => "domains",
1072        _ => "other",
1073    }
1074}
1075
1076/// `drift_detected` → "Drift detected".
1077fn sentence(code: &str) -> String {
1078    let text = code.replace(['_', '-', '.'], " ");
1079    let mut chars = text.chars();
1080    match chars.next() {
1081        Some(first) => first.to_uppercase().chain(chars).collect(),
1082        None => text,
1083    }
1084}
1085
1086#[cfg(test)]
1087mod tests {
1088    use super::*;
1089
1090    fn entry(sha: char) -> FileEntry {
1091        serde_json::from_value(serde_json::json!({
1092            "sha256": format!("sha256:{}", sha.to_string().repeat(64)),
1093            "size": 1,
1094            "contentType": "text/html"
1095        }))
1096        .unwrap()
1097    }
1098
1099    #[test]
1100    fn a_release_lists_the_pages_it_changed() {
1101        let before = BTreeMap::from([
1102            ("/index.html".to_string(), entry('a')),
1103            ("/old/index.html".to_string(), entry('b')),
1104            ("/sitemap.xml".to_string(), entry('c')),
1105        ]);
1106        let after = BTreeMap::from([
1107            ("/index.html".to_string(), entry('d')),
1108            ("/new/index.html".to_string(), entry('e')),
1109            ("/sitemap.xml".to_string(), entry('f')),
1110        ]);
1111        let (pages, other) = page_changes(&before, &after);
1112        let words: Vec<(&str, &str)> =
1113            pages.iter().map(|p| (p.path.as_str(), p.change.text.as_str())).collect();
1114        assert_eq!(
1115            words,
1116            [
1117                ("/index.html", "Changed"),
1118                ("/new/index.html", "New page"),
1119                ("/old/index.html", "Removed")
1120            ]
1121        );
1122        assert_eq!(other, 1);
1123    }
1124
1125    #[test]
1126    fn reasons_read_as_sentences() {
1127        assert_eq!(sentence("drift_detected"), "Drift detected");
1128        assert_eq!(
1129            source_words(&ReleaseSource::Rollback { to_seq: 3 }),
1130            "Rolled back to release 3"
1131        );
1132    }
1133}