Skip to main content

adk_website/ui/
charter.rs

1//! Charter review as cards, one per section, signed by every required signer (spec 3.5 §7.6,
2//! §7.18 stage 5, §8.2 "charter cards", A-I14, A-I23).
3//!
4//! The draft is the kind template's, filled from the interview. The owner reads each section
5//! as a card and either says it looks right or changes it; a change asks for signatures anew,
6//! because a signature is for the text that was read. Once every section has been read, each
7//! person the approval chain for charter changes requires signs in their role — each a
8//! distinct person, none an agent — on the charter's signing request in the site's approval
9//! service, which the back office, the kernel's inbox and chat cards sign too; the version is
10//! committed through the kernel's audited commit (`website.approval_chain.satisfied`,
11//! `website.charter.committed`) with the request as the decision.
12
13use std::collections::BTreeSet;
14
15use adk_core::Result;
16use adk_core::principal::SubjectRef;
17use adk_kernel::charter::{CHARTER_ACTION, CharterVersion, RoleApproval};
18use awp_types::{
19    Charter, Direction, GuardrailAction, RedLine, RedLineKind, Role, RoleHolder, SpendCategory,
20    Urgency,
21};
22use schemars::JsonSchema;
23use serde::{Deserialize, Serialize};
24
25use super::words::{self, money};
26use super::{
27    FieldKind, FieldSpec, FormValues, Line, Pill, Tone, WebsiteDesk, forbidden, invalid, kernel,
28    optional, required, unavailable,
29};
30
31impl WebsiteDesk {
32    pub(crate) async fn save_charter(&self) -> super::saved::SavedCharter {
33        let state = self.inner.charter.lock().await;
34        super::saved::SavedCharter {
35            draft: state.draft.clone(),
36            reviewed: state.reviewed.clone(),
37            committed: state.committed.clone(),
38        }
39    }
40
41    pub(crate) async fn restore_charter(&self, saved: super::saved::SavedCharter) {
42        let mut state = self.inner.charter.lock().await;
43        state.draft = saved.draft;
44        state.reviewed = saved.reviewed;
45        state.committed = saved.committed;
46    }
47}
48
49/// The sections of a charter, in the order the cards show them.
50pub const SECTIONS: [&str; 11] = [
51    "purpose",
52    "goals",
53    "guardrails",
54    "authority",
55    "thresholds",
56    "budget",
57    "voice",
58    "never",
59    "reporting",
60    "people",
61    "public",
62];
63
64#[derive(Default)]
65pub(crate) struct State {
66    pub(crate) draft: Option<Charter>,
67    pub(crate) reviewed: BTreeSet<String>,
68    pub(crate) committed: Option<CharterVersion>,
69}
70
71/// One section of the charter as a card (spec 3.5 §7.18 stage 5).
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
73#[serde(rename_all = "camelCase")]
74pub struct SectionCard {
75    /// The section's id.
76    pub id: String,
77    /// Its heading.
78    pub title: String,
79    /// What it decides, in one line.
80    pub summary: String,
81    /// What the draft says.
82    pub lines: Vec<Line>,
83    /// A rule that applies to it.
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub note: Option<String>,
86    /// Whether the owner has read it.
87    pub reviewed: bool,
88    /// What can be changed here; empty when nothing can.
89    pub fields: Vec<FieldSpec>,
90}
91
92/// A signature the charter needs (spec 3.5 A-I23).
93#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
94#[serde(rename_all = "camelCase")]
95pub struct SignerLine {
96    /// The role, as sent back to sign.
97    pub role: String,
98    /// The role's name.
99    pub label: String,
100    /// The people who hold it.
101    pub holders: Vec<String>,
102    /// Who signed in it, if anyone.
103    #[serde(default, skip_serializing_if = "Option::is_none")]
104    pub signed_by: Option<String>,
105    /// When.
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub signed_at: Option<chrono::DateTime<chrono::Utc>>,
108}
109
110/// The committed version.
111#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
112#[serde(rename_all = "camelCase")]
113pub struct CommittedView {
114    /// The version.
115    pub version: u32,
116    /// When it took effect.
117    pub at: chrono::DateTime<chrono::Utc>,
118    /// Who signed it.
119    pub signed_by: Vec<String>,
120}
121
122/// The charter under review (spec 3.5 §7.18 stage 5).
123#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
124#[serde(rename_all = "camelCase")]
125pub struct CharterReview {
126    /// The version it becomes.
127    pub version: u32,
128    /// The site kind's template it started from.
129    pub kind: String,
130    /// Where it stands.
131    pub status: Pill,
132    /// One card per section.
133    pub sections: Vec<SectionCard>,
134    /// Sections read so far.
135    pub reviewed: usize,
136    /// The signatures it needs, in the chain's order.
137    pub signers: Vec<SignerLine>,
138    /// The roles the viewer may sign in now.
139    pub can_sign: Vec<String>,
140    /// Why it cannot be signed yet.
141    pub problems: Vec<String>,
142    /// The committed version, once every signer has signed.
143    #[serde(default, skip_serializing_if = "Option::is_none")]
144    pub committed: Option<CommittedView>,
145}
146
147/// A change to the charter under review.
148#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
149#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
150pub enum CharterCommand {
151    /// The section looks right.
152    Review {
153        /// The section.
154        section: String,
155    },
156    /// Change the section's fields; clears every signature.
157    Edit {
158        /// The section.
159        section: String,
160        /// The new values, by field id.
161        values: FormValues,
162    },
163    /// Sign in `role` (A-I23).
164    Sign {
165        /// The role, such as `owner`.
166        role: String,
167    },
168}
169
170fn hours(duration: std::time::Duration) -> String {
171    let secs = duration.as_secs();
172    if secs >= 86_400 && secs.is_multiple_of(86_400) {
173        let days = secs / 86_400;
174        if days == 1 { "a day".into() } else { format!("{days} days") }
175    } else {
176        format!("{} hours", secs / 3_600)
177    }
178}
179
180fn channels(charter: &Charter, urgency: Urgency) -> String {
181    let names: Vec<String> = charter
182        .reporting
183        .routes
184        .iter()
185        .filter(|route| route.urgency == urgency)
186        .flat_map(|route| route.channels.iter().map(|c| c.as_str().to_string()))
187        .collect();
188    if names.is_empty() { "Not set".into() } else { names.join(", ") }
189}
190
191fn job_title(job: &str) -> String {
192    crate::jobs::job(job).map_or_else(|| job.replace('-', " "), |spec| spec.title.to_string())
193}
194
195fn chain_words(roles: &[Role]) -> String {
196    let names: Vec<&str> = roles.iter().map(|role| words::role(*role)).collect();
197    names.join(", then ").to_lowercase()
198}
199
200/// The cards of `charter`.
201pub(crate) fn cards(
202    charter: &Charter,
203    reviewed: &BTreeSet<String>,
204    estimate: Option<&crate::onboarding::cost::RunningCostEstimate>,
205) -> Vec<SectionCard> {
206    let currency = charter.budget.currency.clone();
207    let exponent = words::minor_exponent(&currency);
208    let card = |id: &str, title: &str, summary: &str, lines: Vec<Line>| SectionCard {
209        id: id.into(),
210        title: title.into(),
211        summary: summary.into(),
212        lines,
213        note: None,
214        reviewed: reviewed.contains(id),
215        fields: Vec::new(),
216    };
217    let mut out = Vec::new();
218
219    let mut purpose = card(
220        "purpose",
221        "What the site is for",
222        "The mission, in your words, and the pillars of the strategy",
223        vec![
224            Line::new("Mission", charter.mission.clone()),
225            Line::new(
226                "Strategy",
227                charter.strategy.iter().map(|p| p.name.clone()).collect::<Vec<_>>().join(" · "),
228            ),
229        ],
230    );
231    purpose.fields = vec![
232        FieldSpec::new("mission", "Mission", FieldKind::LongText)
233            .required()
234            .value(&charter.mission),
235    ];
236    out.push(purpose);
237
238    let mut goals = card(
239        "goals",
240        "Goals and how they are measured",
241        "What the site works towards, and the measure behind each goal",
242        Vec::new(),
243    );
244    for goal in &charter.goals {
245        let measures: Vec<String> = goal
246            .kpis
247            .iter()
248            .filter_map(|id| charter.kpis.iter().find(|k| &k.id == id))
249            .map(|k| k.name.clone())
250            .collect();
251        goals
252            .lines
253            .push(Line::new(goal.name.clone(), format!("Measured by {}", measures.join(", "))));
254    }
255    for kpi in &charter.kpis {
256        let direction = match kpi.direction {
257            Direction::Down => "lower is better",
258            _ => "higher is better",
259        };
260        let target = match (&kpi.baseline, &kpi.target) {
261            (Some(_), Some(target)) => format!("target {}", words::number(target.value)),
262            _ => "no target until it has a baseline".into(),
263        };
264        goals.lines.push(Line::new(
265            kpi.name.clone(),
266            format!("From {}, {direction}; {target}", kpi.source.to_string().replace('_', " ")),
267        ));
268    }
269    goals.note = Some(
270        "Each measure runs for 14 days to find its baseline. Targets are yours to set after \
271         that; the site only proposes ranges."
272            .into(),
273    );
274    out.push(goals);
275
276    let mut guardrails = card(
277        "guardrails",
278        "Guardrails",
279        "Limits that stop a job, whatever the goals say",
280        charter
281            .guardrails
282            .iter()
283            .map(|g| {
284                let breach = match g.breach {
285                    awp_types::Breach::Below => "below",
286                    _ => "above",
287                };
288                let action = match g.action {
289                    GuardrailAction::PauseJob => "pause the job and tell you",
290                    _ => "tell you",
291                };
292                Line::new(
293                    g.metric.0.replace(['.', '_'], " "),
294                    format!(
295                        "If it goes {breach} {} over {}, {action}",
296                        words::number(g.threshold),
297                        hours(g.window)
298                    ),
299                )
300            })
301            .collect(),
302    );
303    guardrails.note = Some("Guardrails override growth targets.".into());
304    out.push(guardrails);
305
306    let mut authority = card(
307        "authority",
308        "What the site may do alone",
309        "How much each job does without asking you first",
310        charter
311            .authority
312            .iter()
313            .map(|a| Line::new(job_title(&a.job), words::level(a.level)))
314            .collect(),
315    );
316    authority.note = Some(
317        "Every job starts by suggesting or just looking for the first week. Only you can let a \
318         job do more; the site can only do less."
319            .into(),
320    );
321    out.push(authority);
322    out.push(thresholds_card(charter, card("thresholds", "When the site asks you", "When a lead comes to you, how long the site's own pages wait, and the amounts that wait for your yes", Vec::new())));
323
324    let mut budget = card(
325        "budget",
326        "Budget",
327        "What the site may spend each month, by category",
328        charter
329            .budget
330            .caps
331            .iter()
332            .map(|(category, cap)| {
333                Line::new(words::category(*category), format!("{} a month", money(*cap, &currency)))
334            })
335            .collect(),
336    );
337    if let Some(estimate) = estimate {
338        let fits = estimate.fits(&charter.budget);
339        budget.lines.push(Line::new(
340            "Estimated running cost",
341            format!(
342                "{} a month — {}",
343                money(estimate.total, &currency),
344                if fits { "inside the budget" } else { "over the budget" }
345            ),
346        ));
347    }
348    budget.note = Some(
349        "The site never raises a limit, adds a payment method or opens an account; those are \
350         yours."
351            .into(),
352    );
353    budget.fields = [
354        SpendCategory::Hosting,
355        SpendCategory::Models,
356        SpendCategory::Domains,
357        SpendCategory::Advertising,
358        SpendCategory::Other,
359    ]
360    .into_iter()
361    .map(|category| {
362        let cap = charter.budget.caps.get(&category).copied().unwrap_or(0);
363        let value = format!("{:.*}", exponent.max(0) as usize, cap as f64 / 10f64.powi(exponent));
364        FieldSpec::new(
365            category_id(category),
366            &format!("{} ({currency} a month)", words::category(category)),
367            FieldKind::Number,
368        )
369        .value(value)
370    })
371    .collect();
372    out.push(budget);
373
374    let mut voice = card(
375        "voice",
376        "How the site speaks",
377        "Tone, languages and the line that says an AI agent wrote a message",
378        vec![
379            Line::new("Tone", charter.voice.tone.clone()),
380            Line::new(
381                "Languages",
382                charter.voice.languages.iter().map(|l| l.as_str()).collect::<Vec<_>>().join(", "),
383            ),
384            Line::new("On every message it writes", charter.voice.disclosure.clone()),
385        ],
386    );
387    voice.fields =
388        vec![FieldSpec::new("tone", "Tone", FieldKind::Text).required().value(&charter.voice.tone)];
389    out.push(voice);
390
391    let mut never = card(
392        "never",
393        "Never",
394        "Claims, topics and actions the site must never touch",
395        charter
396            .red_lines
397            .iter()
398            .map(|line| {
399                let kind = match line.kind {
400                    RedLineKind::Claim => "Never claim",
401                    RedLineKind::Topic => "Never discuss",
402                    _ => "Never do",
403                };
404                Line::new(kind, line.text.clone())
405            })
406            .collect(),
407    );
408    never.fields = vec![FieldSpec::new("never", "One per line", FieldKind::LongText).value(
409        charter.red_lines.iter().map(|line| line.text.clone()).collect::<Vec<_>>().join("\n"),
410    )];
411    out.push(never);
412
413    let quiet = charter.reporting.quiet_hours.as_ref();
414    let mut reporting = card(
415        "reporting",
416        "Reports and alarms",
417        "When the site reports, and how it reaches you when something is urgent",
418        vec![
419            Line::new("Review", "Every week, on the web home and on your channel"),
420            Line::new("Urgent", channels(charter, Urgency::P1)),
421            Line::new("Within the hour", channels(charter, Urgency::P2)),
422            Line::new(
423                "Quiet time",
424                quiet.map_or_else(
425                    || "None".to_string(),
426                    |q| {
427                        format!(
428                            "{}–{} {}",
429                            q.start.format("%H:%M"),
430                            q.end.format("%H:%M"),
431                            q.timezone
432                        )
433                    },
434                ),
435            ),
436        ],
437    );
438    reporting.note =
439        Some("Urgent alarms reach you even in quiet time, until you acknowledge them.".into());
440    reporting.fields = vec![
441        FieldSpec::new("quietStart", "Quiet time starts", FieldKind::Time)
442            .value(quiet.map(|q| q.start.format("%H:%M").to_string()).unwrap_or_default()),
443        FieldSpec::new("quietEnd", "Quiet time ends", FieldKind::Time)
444            .value(quiet.map(|q| q.end.format("%H:%M").to_string()).unwrap_or_default()),
445    ];
446    out.push(reporting);
447
448    let mut people = card(
449        "people",
450        "People and approvals",
451        "Who holds each role, and who must approve what",
452        Vec::new(),
453    );
454    for holder in &charter.governance.roles {
455        let roles: Vec<&str> = holder.roles.iter().map(|r| words::role(*r)).collect();
456        people.lines.push(Line::new(holder.principal.clone(), roles.join(", ")));
457    }
458    for chain in &charter.governance.approval_chains {
459        let action = match chain.action.as_str() {
460            "charter_change" => "Charter changes".to_string(),
461            "publish" => "Publishing".to_string(),
462            other => other.replace('_', " "),
463        };
464        people
465            .lines
466            .push(Line::new(action, format!("Approved by the {}", chain_words(&chain.roles))));
467    }
468    people.note = Some(
469        "Each approval in a chain is a different person, and the person who proposes a change \
470         cannot approve it. No agent holds a role."
471            .into(),
472    );
473    people.fields = vec![
474        FieldSpec::new("person", "Add a person", FieldKind::Text)
475            .hint("The account they sign in with"),
476        FieldSpec::new("role", "In the role", FieldKind::Choice).options(
477            [Role::Publisher, Role::Editor, Role::Approver, Role::Owner, Role::Auditor]
478                .into_iter()
479                .map(|role| (words::role_id(role).to_string(), words::role(role).to_string())),
480        ),
481    ];
482    out.push(people);
483
484    let mut public = card(
485        "public",
486        "What the site publishes about itself",
487        "Usage terms for AI and search, its policies, consent and how to reach you",
488        vec![
489            Line::new(
490                "Use by AI and search",
491                charter.public.usage.clone().unwrap_or_else(|| "The defaults".into()),
492            ),
493            Line::new(
494                "Policies",
495                charter
496                    .public
497                    .policies
498                    .iter()
499                    .map(|p| p.name.replace('-', " "))
500                    .collect::<Vec<_>>()
501                    .join(", "),
502            ),
503            Line::new(
504                "Consent asked for",
505                if charter.public.consent_scopes.is_empty() {
506                    "Nothing yet".to_string()
507                } else {
508                    charter
509                        .public
510                        .consent_scopes
511                        .iter()
512                        .map(|s| s.as_str().replace('_', " "))
513                        .collect::<Vec<_>>()
514                        .join(", ")
515                },
516            ),
517            Line::new(
518                "Contact",
519                charter.public.contact.email.clone().unwrap_or_else(|| "The contact page".into()),
520            ),
521        ],
522    );
523    public.fields = vec![
524        FieldSpec::new("email", "Public contact email", FieldKind::Email)
525            .value(charter.public.contact.email.clone().unwrap_or_default()),
526    ];
527    out.push(public);
528    out
529}
530
531/// The amounted capabilities `charter`'s kind declares, which an amount threshold can hold
532/// (spec 3.5 §7.4).
533fn amounted(charter: &Charter) -> Vec<&'static str> {
534    crate::kinds::template(charter.kind)
535        .capabilities
536        .into_iter()
537        .filter(|name| crate::packs::AMOUNTED.contains(name))
538        .collect()
539}
540
541/// A capability's name in plain words: `place_order` is "Place order".
542fn capability_words(name: &str) -> String {
543    let words = name.replace('_', " ");
544    let mut chars = words.chars();
545    chars.next().map_or_else(String::new, |first| first.to_uppercase().chain(chars).collect())
546}
547
548/// The owner's settings as a card (spec 3.5 §5 S8, S10, §7.4, §7.6): the charter's
549/// `handoffThreshold`, `publishDelayHours` and `amountThresholds`, or the site's defaults.
550fn thresholds_card(charter: &Charter, mut card: SectionCard) -> SectionCard {
551    let currency = &charter.budget.currency;
552    let exponent = words::minor_exponent(currency);
553    let default = crate::leads::DEFAULT_HANDOFF_THRESHOLD;
554    card.lines.push(Line::new(
555        "A lead comes to you",
556        match charter.handoff_threshold {
557            Some(threshold) => format!("When it scores {threshold} of 100"),
558            None => format!("When it scores {} of 100, the site's default", words::number(default)),
559        },
560    ));
561    card.lines.push(Line::new(
562        "Pages the site writes on its own",
563        match charter.publish_delay_hours {
564            Some(hours) => format!("Wait {hours} hours before they can go live"),
565            None => format!(
566                "Wait {} hours before they can go live, the site's default",
567                crate::publish_delay::DEFAULT_PUBLISH_DELAY_HOURS
568            ),
569        },
570    ));
571    let capabilities = amounted(charter);
572    for name in &capabilities {
573        let value = match charter.amount_thresholds.get(*name) {
574            Some(amount) => format!("Above {} waits for you", money(*amount, currency)),
575            None => "Not set: the site's defaults apply".to_string(),
576        };
577        card.lines.push(Line::new(capability_words(name), value));
578    }
579    card.note = Some(
580        "A setting left empty keeps the site's default. Amount limits change what the site \
581         publishes to agents, so they apply when the site next starts."
582            .into(),
583    );
584    let mut fields = vec![
585        FieldSpec::new("handoff", "Hand a lead to you at this score (0 to 100)", FieldKind::Number)
586            .value(charter.handoff_threshold.map(|t| t.to_string()).unwrap_or_default()),
587        FieldSpec::new("publishDelay", "Hours the site's own pages wait", FieldKind::Number)
588            .value(charter.publish_delay_hours.map(|h| h.to_string()).unwrap_or_default()),
589    ];
590    for name in capabilities {
591        let value = charter.amount_thresholds.get(name).map_or_else(String::new, |amount| {
592            format!("{:.*}", exponent.max(0) as usize, *amount as f64 / 10f64.powi(exponent))
593        });
594        fields.push(
595            FieldSpec::new(
596                &format!("above_{name}"),
597                &format!("{} above ({currency}) waits for you", capability_words(name)),
598                FieldKind::Number,
599            )
600            .value(value),
601        );
602    }
603    card.fields = fields;
604    card
605}
606
607/// Applies the `thresholds` card's `values` to `charter`; an empty field clears its setting.
608fn apply_thresholds(charter: &mut Charter, values: &FormValues) -> Result<()> {
609    charter.handoff_threshold = match optional(values, "handoff") {
610        None => None,
611        Some(text) => Some(
612            text.trim()
613                .parse::<u8>()
614                .ok()
615                .filter(|threshold| *threshold <= 100)
616                .ok_or_else(|| invalid("website.charter.handoff", "the score is 0 to 100"))?,
617        ),
618    };
619    charter.publish_delay_hours = match optional(values, "publishDelay") {
620        None => None,
621        Some(text) => Some(text.trim().parse::<u32>().map_err(|_| {
622            invalid("website.charter.publish_delay", "the wait is a whole number of hours")
623        })?),
624    };
625    let exponent = words::minor_exponent(&charter.budget.currency);
626    for name in amounted(charter) {
627        match optional(values, &format!("above_{name}")) {
628            None => {
629                charter.amount_thresholds.remove(name);
630            }
631            Some(text) => {
632                let amount: f64 = text.replace(',', "").trim().parse().map_err(|_| {
633                    invalid(
634                        "website.charter.amount",
635                        format!("{} is an amount such as 250.00", capability_words(name)),
636                    )
637                })?;
638                if !(0.0..=1e12).contains(&amount) {
639                    return Err(invalid("website.charter.amount", "an amount is zero or more"));
640                }
641                let minor = (amount * 10f64.powi(exponent)).round() as u64;
642                charter.amount_thresholds.insert(name.to_string(), minor);
643            }
644        }
645    }
646    Ok(())
647}
648
649fn category_id(category: SpendCategory) -> &'static str {
650    match category {
651        SpendCategory::Hosting => "hosting",
652        SpendCategory::Models => "models",
653        SpendCategory::Domains => "domains",
654        SpendCategory::Advertising => "advertising",
655        _ => "other",
656    }
657}
658
659fn parse_time(text: &str, label: &str) -> Result<chrono::NaiveTime> {
660    chrono::NaiveTime::parse_from_str(text.trim(), "%H:%M")
661        .map_err(|_| invalid("website.charter.time", format!("{label} is a time such as 21:00")))
662}
663
664/// Applies `values` to `section` of `charter`.
665pub(crate) fn apply_edit(charter: &mut Charter, section: &str, values: &FormValues) -> Result<()> {
666    match section {
667        "purpose" => charter.mission = required(values, "mission", "The mission")?.to_string(),
668        "voice" => charter.voice.tone = required(values, "tone", "The tone")?.to_string(),
669        "budget" => {
670            let exponent = words::minor_exponent(&charter.budget.currency);
671            for category in [
672                SpendCategory::Hosting,
673                SpendCategory::Models,
674                SpendCategory::Domains,
675                SpendCategory::Advertising,
676                SpendCategory::Other,
677            ] {
678                let Some(text) = optional(values, category_id(category)) else { continue };
679                let amount: f64 = text.replace(',', "").parse().map_err(|_| {
680                    invalid(
681                        "website.charter.amount",
682                        format!("{} is an amount such as 25.00", words::category(category)),
683                    )
684                })?;
685                if !(0.0..=1e12).contains(&amount) {
686                    return Err(invalid("website.charter.amount", "an amount is zero or more"));
687                }
688                let minor = (amount * 10f64.powi(exponent)).round() as u64;
689                if minor == 0 {
690                    charter.budget.caps.remove(&category);
691                } else {
692                    charter.budget.caps.insert(category, minor);
693                }
694            }
695        }
696        "never" => {
697            let lines: Vec<&str> = values
698                .get("never")
699                .map(|text| text.lines().map(str::trim).filter(|line| !line.is_empty()).collect())
700                .unwrap_or_default();
701            let mut kept: Vec<RedLine> = Vec::new();
702            for line in lines {
703                let kind = charter
704                    .red_lines
705                    .iter()
706                    .find(|held| held.text == line)
707                    .map_or(RedLineKind::Claim, |held| held.kind);
708                kept.push(RedLine { kind, text: line.to_string() });
709            }
710            charter.red_lines = kept;
711        }
712        "reporting" => {
713            let start = optional(values, "quietStart");
714            let end = optional(values, "quietEnd");
715            match (start, end) {
716                (None, None) => charter.reporting.quiet_hours = None,
717                (Some(start), Some(end)) => {
718                    let start = parse_time(start, "The start")?;
719                    let end = parse_time(end, "The end")?;
720                    let timezone = charter
721                        .reporting
722                        .quiet_hours
723                        .as_ref()
724                        .map_or_else(|| "UTC".to_string(), |q| q.timezone.clone());
725                    charter.reporting.quiet_hours =
726                        Some(awp_types::QuietHours { start, end, timezone });
727                }
728                _ => {
729                    return Err(invalid(
730                        "website.charter.quiet",
731                        "quiet time needs both a start and an end",
732                    ));
733                }
734            }
735        }
736        "people" => {
737            let person = required(values, "person", "The person's account")?;
738            let role = optional(values, "role")
739                .and_then(words::role_from)
740                .ok_or_else(|| invalid("website.charter.role", "choose a role"))?;
741            if adk_kernel::charter::is_agent_principal(person) {
742                return Err(forbidden(
743                    "website.charter.agent_role",
744                    format!("{person} is an agent: no agent holds a role (spec 3.5 §7.6)"),
745                ));
746            }
747            match charter.governance.roles.iter_mut().find(|held| held.principal == person) {
748                Some(held) if !held.roles.contains(&role) => held.roles.push(role),
749                Some(_) => {}
750                None => charter
751                    .governance
752                    .roles
753                    .push(RoleHolder { principal: person.to_string(), roles: vec![role] }),
754            }
755        }
756        "public" => charter.public.contact.email = optional(values, "email").map(str::to_string),
757        "thresholds" => apply_thresholds(charter, values)?,
758        "goals" | "guardrails" | "authority" => {
759            return Err(invalid(
760                "website.charter.fixed",
761                "this section changes later: targets after a baseline, levels by promotion",
762            ));
763        }
764        other => {
765            return Err(invalid("website.charter.section", format!("no section '{other}'")));
766        }
767    }
768    Ok(())
769}
770
771/// The chain's signer lines with `signatures` placed on them, each person once.
772fn signer_lines(
773    charter: &Charter,
774    governing: &awp_types::Governance,
775    signatures: &[RoleApproval],
776) -> Vec<SignerLine> {
777    let roles = governing
778        .approval_chains
779        .iter()
780        .find(|chain| chain.action == CHARTER_ACTION)
781        .map(|chain| chain.roles.clone())
782        .unwrap_or_else(|| vec![Role::Owner]);
783    let _ = charter;
784    let mut used: Vec<&str> = Vec::new();
785    roles
786        .iter()
787        .map(|role| {
788            let signature = signatures
789                .iter()
790                .find(|s| s.role == *role && !used.contains(&s.principal.id.as_str()));
791            if let Some(signature) = signature {
792                used.push(signature.principal.id.as_str());
793            }
794            SignerLine {
795                role: words::role_id(*role).into(),
796                label: words::role(*role).into(),
797                holders: governing.holders(*role).map(str::to_string).collect(),
798                signed_by: signature.map(|s| s.principal.id.clone()),
799                signed_at: signature.map(|s| s.at),
800            }
801        })
802        .collect()
803}
804
805impl WebsiteDesk {
806    /// The governance that approves the next charter version: the charter in force, or the
807    /// draft's for a site's first charter (spec 3.5 §7.6).
808    async fn governing(&self, draft: &Charter) -> Result<awp_types::Governance> {
809        if let Some(charters) = &self.inner.charters
810            && let Some(current) = charters.current(self.inner.site.id).await.map_err(kernel)?
811        {
812            return Ok(current.charter.governance);
813        }
814        Ok(draft.governance.clone())
815    }
816
817    /// The charter under review as `person` sees it, `None` before a draft exists (spec 3.5
818    /// §7.18 stage 5).
819    ///
820    /// # Errors
821    ///
822    /// Returns the charter store's error.
823    pub async fn charter_review(&self, person: &str) -> Result<Option<CharterReview>> {
824        let state = self.inner.charter.lock().await;
825        let Some(draft) = state.draft.clone() else { return Ok(None) };
826        let reviewed = state.reviewed.clone();
827        let mut committed = state.committed.clone();
828        drop(state);
829        let runtime = self.runtime().await;
830        let mut request = runtime.charter_request(&draft).await?;
831        // People may have signed on another surface — the back office, the kernel's inbox, a
832        // chat card — so a request they completed is committed now.
833        if committed.is_none() && request.is_some() {
834            for version in runtime.settle_charters().await? {
835                self.adopt_charter(&version).await?;
836            }
837            committed = self.inner.charter.lock().await.committed.clone();
838            if committed.is_none() {
839                request = runtime.charter_request(&draft).await?;
840            }
841        }
842        let signatures = request.map(|request| request.signatures).unwrap_or_default();
843        let estimate = self.estimate(&draft).await;
844        let sections = cards(&draft, &reviewed, estimate.as_ref());
845        let governing = self.governing(&draft).await?;
846        let signers = signer_lines(&draft, &governing, &signatures);
847        let mut problems: Vec<String> = match draft.validate() {
848            Ok(()) => Vec::new(),
849            Err(error) => error.violations.iter().map(ToString::to_string).collect(),
850        };
851        if reviewed.len() < SECTIONS.len() {
852            problems.push(format!(
853                "Read every section first: {} of {} done",
854                reviewed.len(),
855                SECTIONS.len()
856            ));
857        }
858        let can_sign = if committed.is_some() || !problems.is_empty() {
859            Vec::new()
860        } else {
861            signers
862                .iter()
863                .filter(|line| line.signed_by.is_none())
864                .filter(|line| line.holders.iter().any(|h| h == person))
865                .filter(|_| !signatures.iter().any(|s| s.principal.id == person))
866                .map(|line| line.role.clone())
867                .collect::<BTreeSet<_>>()
868                .into_iter()
869                .collect()
870        };
871        let status = match (&committed, signatures.is_empty()) {
872            (Some(_), _) => Pill::new("Signed", Tone::Good),
873            (None, false) => Pill::new("Waiting for signatures", Tone::Waiting),
874            (None, true) => Pill::new("Draft", Tone::Neutral),
875        };
876        Ok(Some(CharterReview {
877            version: committed.as_ref().map_or(draft.version, CharterVersion::version),
878            kind: crate::kinds::template(draft.kind).title.to_string(),
879            status,
880            reviewed: reviewed.len(),
881            sections,
882            signers,
883            can_sign,
884            problems,
885            committed: committed.map(|version| CommittedView {
886                version: version.version(),
887                at: version.committed_at,
888                signed_by: version
889                    .decision
890                    .approvals
891                    .iter()
892                    .map(|approval| approval.principal.id.clone())
893                    .collect(),
894            }),
895        }))
896    }
897
898    /// Carries out `command` on the charter under review for `person` (spec 3.5 §7.18
899    /// stage 5, A-I23). Edits come from the onboarding owner; a signature from any person the
900    /// governing approval chain names, in a role they hold. Returns the committed version
901    /// once every required signer has signed.
902    ///
903    /// # Errors
904    ///
905    /// `NotFound` without a draft; `Forbidden` for a person who may not edit or sign;
906    /// `InvalidInput` for an unknown section, a bad value, or signing before every section
907    /// was read or while the draft is invalid; the charter store's errors.
908    pub async fn charter_command(
909        &self,
910        person: &str,
911        command: CharterCommand,
912    ) -> Result<Option<CharterVersion>> {
913        let result = self.charter_command_unsaved(person, command).await;
914        if result.is_ok() {
915            self.persist().await;
916        }
917        result
918    }
919
920    async fn charter_command_unsaved(
921        &self,
922        person: &str,
923        command: CharterCommand,
924    ) -> Result<Option<CharterVersion>> {
925        self.inner.charters.as_ref().ok_or_else(|| unavailable("The charter store"))?;
926        let mut state = self.inner.charter.lock().await;
927        if state.committed.is_some() {
928            return Err(invalid(
929                "website.charter.committed",
930                "this version is signed; a change is a new version",
931            ));
932        }
933        let Some(draft) = state.draft.clone() else {
934            return Err(super::not_found(
935                "website.charter.no_draft",
936                "there is no charter draft yet: it is drafted when the interview is done",
937            ));
938        };
939        match command {
940            CharterCommand::Review { section } => {
941                self.require(person, &[Role::Owner], "Reading the charter for signature").await?;
942                if !SECTIONS.contains(&section.as_str()) {
943                    return Err(invalid(
944                        "website.charter.section",
945                        format!("no section '{section}'"),
946                    ));
947                }
948                state.reviewed.insert(section);
949                Ok(None)
950            }
951            CharterCommand::Edit { section, values } => {
952                self.require(person, &[Role::Owner], "Changing the charter").await?;
953                let mut draft = draft;
954                apply_edit(&mut draft, &section, &values)?;
955                state.draft = Some(draft);
956                state.reviewed.insert(section);
957                Ok(None)
958            }
959            CharterCommand::Sign { role } => {
960                let role = words::role_from(&role)
961                    .ok_or_else(|| invalid("website.charter.role", format!("no role '{role}'")))?;
962                if adk_kernel::charter::is_agent_principal(person) {
963                    return Err(forbidden(
964                        "website.charter.agent_signer",
965                        format!("{person} is not a person: no agent signs a charter (A-I23)"),
966                    ));
967                }
968                if state.reviewed.len() < SECTIONS.len() {
969                    return Err(invalid(
970                        "website.charter.unread",
971                        "read every section before signing",
972                    ));
973                }
974                if let Err(error) = draft.validate() {
975                    return Err(invalid("website.charter.invalid", error.to_string()));
976                }
977                let governing = self.governing(&draft).await?;
978                if !governing.holds(person, role) {
979                    return Err(forbidden(
980                        "website.charter.not_a_signer",
981                        format!(
982                            "{person} does not hold the {} role",
983                            words::role(role).to_lowercase()
984                        ),
985                    ));
986                }
987                let runtime = self.runtime().await;
988                // The Steward drafts the charter from the interview, so it asks; no agent signs.
989                let steward = self.inner.site.principal("steward");
990                let request = runtime.request_charter(&draft, None, &steward).await?;
991                let signature = RoleApproval::new(role, SubjectRef::human(person), self.now());
992                let Some(version) = runtime.sign_charter(&request.id, signature).await? else {
993                    return Ok(None);
994                };
995                drop(state);
996                self.adopt_charter(&version).await?;
997                Ok(Some(version))
998            }
999        }
1000    }
1001
1002    /// Takes `version` as the committed charter: the desk shows it signed, and its jobs join
1003    /// the autonomy ladder.
1004    async fn adopt_charter(&self, version: &CharterVersion) -> Result<()> {
1005        if let Some(ladder) = &self.inner.ladder {
1006            crate::jobs::register(ladder, &version.charter).await?;
1007        }
1008        self.inner.charter.lock().await.committed = Some(version.clone());
1009        Ok(())
1010    }
1011
1012    /// The running-cost estimate of `charter`'s team, when the desk knows what a month
1013    /// looks like (spec 3.5 §7.22).
1014    pub(crate) async fn estimate(
1015        &self,
1016        charter: &Charter,
1017    ) -> Option<crate::onboarding::cost::RunningCostEstimate> {
1018        let inputs = self.inner.cost.as_ref()?;
1019        let template = crate::kinds::template(charter.kind);
1020        let team = crate::team::SiteTeam::new(self.inner.site.clone(), &template);
1021        Some(crate::onboarding::cost::estimate(&team, inputs))
1022    }
1023}
1024
1025#[cfg(test)]
1026mod tests {
1027    use super::*;
1028    use crate::kinds::{CharterInputs, template};
1029    use crate::team::SiteTeam;
1030    use adk_harness::website::SiteRef;
1031    use awp_types::SiteKind;
1032
1033    fn draft(kind: SiteKind) -> Charter {
1034        let id = uuid::Uuid::new_v4();
1035        let template = template(kind);
1036        let team = SiteTeam::new(SiteRef::new(id, "bakery", "https://bakery.example"), &template);
1037        let inputs = CharterInputs::new(
1038            id,
1039            "Juniper Bakery",
1040            "amina",
1041            "Fresh bread every morning.",
1042            vec!["en".parse().unwrap()],
1043            "KES",
1044        );
1045        template.draft_charter(&team, &inputs)
1046    }
1047
1048    #[test]
1049    fn every_section_is_a_card_in_order() {
1050        let charter = draft(SiteKind::Business);
1051        let cards = cards(&charter, &BTreeSet::new(), None);
1052        let ids: Vec<&str> = cards.iter().map(|c| c.id.as_str()).collect();
1053        assert_eq!(ids, SECTIONS);
1054        let goals = cards.iter().find(|c| c.id == "goals").unwrap();
1055        assert!(
1056            goals
1057                .lines
1058                .iter()
1059                .filter(|l| charter.kpis.iter().any(|k| k.name == l.label))
1060                .all(|l| l.value.contains("no target until it has a baseline")),
1061            "A-I14: {goals:?}"
1062        );
1063    }
1064
1065    #[test]
1066    fn edits_change_only_their_section_and_keep_the_charter_valid() {
1067        let mut charter = draft(SiteKind::Business);
1068        let values = FormValues::from([("models".to_string(), "1,500.00".to_string())]);
1069        apply_edit(&mut charter, "budget", &values).unwrap();
1070        assert_eq!(charter.budget.caps[&SpendCategory::Models], 150_000);
1071        apply_edit(
1072            &mut charter,
1073            "never",
1074            &FormValues::from([(
1075                "never".to_string(),
1076                "Never promise same-day delivery\n".to_string(),
1077            )]),
1078        )
1079        .unwrap();
1080        assert_eq!(charter.red_lines.len(), 1);
1081        assert!(charter.validate().is_ok());
1082        assert!(
1083            apply_edit(&mut charter, "goals", &FormValues::new()).is_err(),
1084            "targets wait for a baseline"
1085        );
1086        let agent = FormValues::from([
1087            ("person".to_string(), "urn:adk:agent:bakery/steward".to_string()),
1088            ("role".to_string(), "publisher".to_string()),
1089        ]);
1090        assert!(apply_edit(&mut charter, "people", &agent).is_err(), "no agent holds a role");
1091    }
1092
1093    /// The owner's settings show on their card, defaults included, and an edit sets them as
1094    /// charter members (spec 3.5 §5 S8, S10, §7.4, §7.6).
1095    #[test]
1096    fn the_thresholds_card_shows_and_sets_the_owners_settings() {
1097        let mut charter = draft(SiteKind::Ecommerce);
1098        let card = |charter: &Charter| {
1099            cards(charter, &BTreeSet::new(), None)
1100                .into_iter()
1101                .find(|card| card.id == "thresholds")
1102                .unwrap()
1103        };
1104        let line = |card: &SectionCard, label: &str| {
1105            card.lines.iter().find(|line| line.label == label).unwrap().value.clone()
1106        };
1107        let before = card(&charter);
1108        assert_eq!(
1109            line(&before, "A lead comes to you"),
1110            "When it scores 70 of 100, the site's default"
1111        );
1112        assert!(line(&before, "Pages the site writes on its own").contains("24 hours"));
1113        assert_eq!(line(&before, "Place order"), "Not set: the site's defaults apply");
1114        assert!(before.fields.iter().any(|field| field.id == "above_place_order"));
1115
1116        let values = FormValues::from([
1117            ("handoff".to_string(), "60".to_string()),
1118            ("publishDelay".to_string(), "48".to_string()),
1119            ("above_place_order".to_string(), "200.00".to_string()),
1120        ]);
1121        apply_edit(&mut charter, "thresholds", &values).unwrap();
1122        assert_eq!((charter.handoff_threshold, charter.publish_delay_hours), (Some(60), Some(48)));
1123        assert_eq!(charter.amount_thresholds.get("place_order"), Some(&20_000));
1124        assert!(charter.validate().is_ok());
1125        let after = card(&charter);
1126        assert_eq!(line(&after, "A lead comes to you"), "When it scores 60 of 100");
1127        assert_eq!(
1128            line(&after, "Pages the site writes on its own"),
1129            "Wait 48 hours before they can go live"
1130        );
1131        assert_eq!(line(&after, "Place order"), "Above KES 200.00 waits for you");
1132
1133        let too_high = FormValues::from([("handoff".to_string(), "120".to_string())]);
1134        assert!(apply_edit(&mut charter, "thresholds", &too_high).is_err());
1135        apply_edit(&mut charter, "thresholds", &FormValues::new()).unwrap();
1136        assert_eq!(
1137            (
1138                charter.handoff_threshold,
1139                charter.publish_delay_hours,
1140                charter.amount_thresholds.len()
1141            ),
1142            (None, None, 0),
1143            "an empty field keeps the site's default"
1144        );
1145    }
1146
1147    #[test]
1148    fn a_two_person_chain_names_a_signer_per_role() {
1149        let mut charter = draft(SiteKind::Government);
1150        charter.governance.approval_chains[0].roles = vec![Role::Owner, Role::Owner];
1151        charter
1152            .governance
1153            .roles
1154            .push(RoleHolder { principal: "baraka".into(), roles: vec![Role::Owner] });
1155        let signatures =
1156            vec![RoleApproval::new(Role::Owner, SubjectRef::human("amina"), chrono::Utc::now())];
1157        let lines = signer_lines(&charter, &charter.governance.clone(), &signatures);
1158        assert_eq!(lines.len(), 2);
1159        assert_eq!(lines[0].signed_by.as_deref(), Some("amina"));
1160        assert_eq!(lines[1].signed_by, None, "one person signs once");
1161    }
1162}