Skip to main content

adk_harness/website/
site.rs

1//! The site runtime the back-office tools act on: `adk-site`'s publishing pipeline, launch
2//! gate, host and media pipeline, the charter store, and the decisions people make
3//! (spec 3.5 §7.6, §7.8, §7.8.1, §7.8.2, A-I18, A-I23).
4
5use std::collections::BTreeMap;
6use std::path::PathBuf;
7use std::sync::Arc;
8
9use adk_core::principal::SubjectRef;
10use adk_core::{
11    AdkError, ApprovalAction, ApprovalPolicy, ApprovalScope, ApprovalService, ApprovalState,
12    ApproverSelector, Clock, ErrorCategory, ErrorComponent, GovernanceControl,
13    InMemoryApprovalStore, InboxQuery, Result, StoreApprovalService, SystemClock,
14    ToolConfirmationRequest,
15};
16use adk_kernel::charter::{
17    CHARTER_ACTION, CharterDirectory, CharterStore, CharterVersion, CommitDecision, RoleApproval,
18    chain_policy, commit_audited, group_role,
19};
20use adk_site::content::{ContentHistory, ContentStore, SiteProject};
21use adk_site::gate::{
22    ClaimCheck, ClaimFinding, GateInput, GateMode, GateReport, LaunchGate, Quarantine,
23};
24use adk_site::generator::SiteGenerator;
25use adk_site::host::SiteHost;
26use adk_site::log::{CHECKPOINT_PATH, SiteLog};
27use adk_site::media::MediaPipeline;
28use adk_site::pipeline::{
29    Announcer, ApprovalDecision, ApprovalGate, ApprovalRequest, ChangeTagSink, Draft, EntryPoint,
30    Preview, PublishingPipeline,
31};
32use adk_site::release::PreviousRelease;
33use async_trait::async_trait;
34use awp_types::{Charter, ContentItem, Digest, Governance, Role};
35use chrono::{DateTime, Utc};
36use serde::{Deserialize, Serialize};
37use serde_json::{Value, json};
38use tokio::sync::Mutex;
39use uuid::Uuid;
40
41use super::drafts::{
42    DraftKind, InMemorySiteDraftStore, SiteDraftStore, StoredDraft, StoredRecord, conflict,
43    store_error,
44};
45use crate::facts::{FactScope, FactStatus, FactStore};
46
47/// The approver a release names when the governed path, not an approval chain, allowed it:
48/// the job's level let the call run, or the owner approved the held call (spec 3.5 §7.8.2
49/// step 4).
50pub const GOVERNED_APPROVER: &str = "adk-harness:governed-path";
51
52/// Which site the runtime serves (spec 3.5 §7.19, A-I22).
53///
54/// `name` is the site's application name: every agent of the site acts as
55/// `urn:adk:agent:{name}/{agent}`, and in agency mode no two sites share one.
56///
57/// # Example
58///
59/// ```rust
60/// use adk_harness::website::SiteRef;
61///
62/// let site = SiteRef::new(uuid::Uuid::nil(), "bakery", "https://bakery.example");
63/// assert_eq!(site.principal("steward"), "urn:adk:agent:bakery/steward");
64/// ```
65#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
66#[serde(rename_all = "camelCase")]
67pub struct SiteRef {
68    /// The charter's `site_id`.
69    pub id: Uuid,
70    /// The site's application name.
71    pub name: String,
72    /// The public origin, such as `https://bakery.example`.
73    pub origin: String,
74}
75
76impl SiteRef {
77    /// A site `id` named `name` served at `origin`.
78    pub fn new(id: Uuid, name: impl Into<String>, origin: impl Into<String>) -> Self {
79        Self { id, name: name.into(), origin: origin.into() }
80    }
81
82    /// The principal of the site's agent `agent`: `urn:adk:agent:{site}/{agent}` (spec 3.5
83    /// §7.19).
84    pub fn principal(&self, agent: &str) -> String {
85        format!("urn:adk:agent:{}/{agent}", self.name)
86    }
87}
88
89pub(crate) fn site_error(error: adk_site::SiteError) -> AdkError {
90    let category = match &error {
91        adk_site::SiteError::NotFound(_) | adk_site::SiteError::ReleaseNotFound { .. } => {
92            ErrorCategory::NotFound
93        }
94        adk_site::SiteError::InvalidContent { .. } | adk_site::SiteError::GateFailed(_) => {
95            ErrorCategory::InvalidInput
96        }
97        adk_site::SiteError::ServerCode { .. } => ErrorCategory::Forbidden,
98        _ => ErrorCategory::Internal,
99    };
100    AdkError::new(ErrorComponent::Tool, category, "website.site", error.to_string())
101}
102
103pub(crate) fn kernel_error(error: adk_kernel::KernelError) -> AdkError {
104    let category = match &error {
105        adk_kernel::KernelError::Unauthorized { .. } => ErrorCategory::Forbidden,
106        adk_kernel::KernelError::Config { .. } => ErrorCategory::InvalidInput,
107        _ => ErrorCategory::Internal,
108    };
109    AdkError::new(ErrorComponent::Tool, category, "website.kernel", error.to_string())
110}
111
112/// A claim check over the harness's long-term facts (spec 3.5 A-I18): every fact an item
113/// cites must be `Known` in the site's scope, so a claim from an `Assumed` fact never
114/// publishes.
115///
116/// # Example
117///
118/// ```rust,ignore
119/// let gate = LaunchGate::new().with_claim_check(Arc::new(FactClaimCheck::new(facts, scope)));
120/// ```
121pub struct FactClaimCheck {
122    facts: Arc<dyn FactStore>,
123    scope: FactScope,
124}
125
126impl FactClaimCheck {
127    /// Checks claims against the facts of `scope` in `facts`.
128    pub fn new(facts: Arc<dyn FactStore>, scope: FactScope) -> Self {
129        Self { facts, scope }
130    }
131}
132
133#[async_trait]
134impl ClaimCheck for FactClaimCheck {
135    async fn unsupported_claims(&self, item: &ContentItem) -> adk_site::Result<Vec<ClaimFinding>> {
136        let mut findings = Vec::new();
137        for cited in &item.sources {
138            let fact = self
139                .facts
140                .get(&cited.0)
141                .await
142                .map_err(|e| adk_site::SiteError::Pipeline(format!("facts: {e}")))?
143                .filter(|fact| self.scope.admits(&fact.scope));
144            let reason = match fact.map(|fact| fact.status) {
145                Some(FactStatus::Known) => continue,
146                Some(FactStatus::Assumed) => "the fact is Assumed; the owner has not confirmed it",
147                Some(_) => "the fact is no longer live",
148                None => "the fact is not in the site's facts",
149            };
150            findings.push(ClaimFinding {
151                claim: cited.0.clone(),
152                fact: Some(cited.clone()),
153                reason: reason.to_string(),
154            });
155        }
156        Ok(findings)
157    }
158}
159
160/// The tool name of a release's approval request (spec 3.5 §7.8.2 step 4).
161pub const SITE_RELEASE_TOOL: &str = "site_release";
162
163/// The tool name of a charter signing request (spec 3.5 §7.6).
164pub const CHARTER_SIGN_TOOL: &str = "charter_sign";
165
166/// The tool name of a job promotion request (spec 3.5 §7.11, A-I13).
167pub const JOB_PROMOTION_TOOL: &str = "job_promotion";
168
169/// The session the site's approval requests are kept under, in the site's application.
170const APPROVAL_SESSION: &str = "site-approvals";
171
172/// What a release vote binds to (spec 3.5 §7.8.2 step 4, A-I23): the site and the
173/// [`change_digest`](adk_site::pipeline::change_digest) of the change — its action class,
174/// proposer, items and media, and the release and generator it was previewed on.
175///
176/// A rebuild of the same change on the same base gives the same fingerprint, so a vote
177/// survives a restart and a new preview; an edit, or another release becoming the base,
178/// gives a new fingerprint and a new request, so earlier votes stop counting.
179///
180/// # Example
181///
182/// ```rust
183/// use adk_harness::website::ReleaseFingerprint;
184/// use awp_types::Digest;
185///
186/// let site = uuid::Uuid::nil();
187/// let change = Digest::from_sha256_bytes([7; 32]);
188/// let fingerprint = ReleaseFingerprint::new(site, &change);
189/// assert_eq!(fingerprint, ReleaseFingerprint::new(site, &change));
190/// assert!(fingerprint.request_id(site).starts_with("site-release-"));
191/// ```
192#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
193pub struct ReleaseFingerprint(String);
194
195impl ReleaseFingerprint {
196    /// The fingerprint of `change` on `site`.
197    pub fn new(site: Uuid, change: &Digest) -> Self {
198        use sha2::Digest as _;
199
200        let digest = sha2::Sha256::digest(format!("{site}\u{1f}{change}").as_bytes());
201        Self(Digest::from_sha256_bytes(digest.into()).to_string())
202    }
203
204    /// The fingerprint as `sha256:<hex>`.
205    pub fn as_str(&self) -> &str {
206        &self.0
207    }
208
209    /// The id of the release's approval request: `site-release-{site}-{first 16 hex digits}`.
210    pub fn request_id(&self, site: Uuid) -> String {
211        let hex = self.0.trim_start_matches("sha256:");
212        format!("site-release-{site}-{}", &hex[..16.min(hex.len())])
213    }
214}
215
216/// The site's decisions people make, as requests in its approval service (spec 3.5 §7.6,
217/// §7.8.2 step 4, §7.11, A-I23): release chains, charter signatures and job promotions.
218///
219/// | The charter | What decides a release |
220/// |---|---|
221/// | names an approval chain for the action class | one [`ApprovalRequest`](adk_core::ApprovalRequest) per [`ReleaseFingerprint`], with one slot per role of the chain, filled by distinct people who hold the role, none the proposer |
222/// | names none | the governed path: the call ran because the job's level allowed it or the owner approved it, recorded as [`GOVERNED_APPROVER`] |
223///
224/// Every surface — the back office, the web desk, the kernel's inbox, a chat card — decides
225/// the same request through the service, which takes each person's roles from the charter
226/// in force ([`CharterDirectory`](adk_kernel::charter::CharterDirectory)), writes every vote
227/// to its audit trail, and settles concurrent votes by compare-and-swap. An early approval
228/// leaves the request pending and records no `site.content.approved`.
229pub struct SiteApprovals {
230    site: SiteRef,
231    charters: Option<Arc<dyn CharterStore>>,
232    service: Arc<dyn ApprovalService>,
233}
234
235impl std::fmt::Debug for SiteApprovals {
236    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
237        f.debug_struct("SiteApprovals").field("site", &self.site).finish_non_exhaustive()
238    }
239}
240
241impl SiteApprovals {
242    /// The approval service the requests live in.
243    pub fn service(&self) -> &Arc<dyn ApprovalService> {
244        &self.service
245    }
246
247    /// The request `id`.
248    ///
249    /// # Errors
250    ///
251    /// The approval service's error.
252    pub async fn get(&self, id: &str) -> Result<Option<adk_core::ApprovalRequest>> {
253        self.service.get(id).await
254    }
255
256    /// Records `by`'s approval of the request `id` read at `version`: a release, a charter
257    /// signature or a promotion (spec 3.5 A-I23).
258    ///
259    /// # Example
260    ///
261    /// ```rust,ignore
262    /// let request = runtime.approvals().get(&ticket).await?.expect("the release's request");
263    /// let after = runtime.approvals().approve(&ticket, request.version, &SubjectRef::human("eva")).await?;
264    /// assert_eq!(after.state, ApprovalState::Pending, "the publisher has not approved yet");
265    /// ```
266    ///
267    /// # Errors
268    ///
269    /// `website.approval.refused` for an agent; the service's `approval.not_an_approver` for
270    /// a person the charter gives none of the request's roles, `approval.self_approval` for
271    /// the proposer, `approval.already_decided` for a second approval by one person, and
272    /// `approval.version_conflict` when the request changed since `version`.
273    pub async fn approve(
274        &self,
275        id: &str,
276        version: u64,
277        by: &SubjectRef,
278    ) -> Result<adk_core::ApprovalRequest> {
279        refuse_agent(by)?;
280        self.service.decide(id, version, adk_core::ApprovalDecision::approve(by.clone())).await
281    }
282
283    /// Records `by`'s refusal of the request `id` read at `version`; only a person who may
284    /// approve it may refuse it.
285    ///
286    /// # Errors
287    ///
288    /// As [`approve`](Self::approve).
289    pub async fn reject(
290        &self,
291        id: &str,
292        version: u64,
293        by: &SubjectRef,
294        reason: &str,
295    ) -> Result<adk_core::ApprovalRequest> {
296        refuse_agent(by)?;
297        self.service
298            .decide(id, version, adk_core::ApprovalDecision::reject(by.clone(), reason))
299            .await
300    }
301
302    /// The site's requests with `tool` in `states`, oldest first.
303    ///
304    /// # Errors
305    ///
306    /// The approval service's error.
307    pub async fn list(
308        &self,
309        tool: &str,
310        states: &[ApprovalState],
311    ) -> Result<Vec<adk_core::ApprovalRequest>> {
312        let mut query = InboxQuery::default()
313            .with_app_name(self.site.name.clone())
314            .with_states(states.iter().copied())
315            .with_limit(adk_core::DEFAULT_APPROVAL_PAGE);
316        let site = self.site.id.to_string();
317        let mut requests = Vec::new();
318        loop {
319            let page = self.service.inbox(query.clone()).await?;
320            requests.extend(page.items.into_iter().filter(|request| {
321                request.tool_name == tool
322                    && request.args_redacted.get("site").and_then(Value::as_str)
323                        == Some(site.as_str())
324            }));
325            match page.next_cursor {
326                Some(next) => query = query.with_cursor(Some(next)),
327                None => return Ok(requests),
328            }
329        }
330    }
331
332    /// Submits the request `id` for `tool` with `args` under `policy`, or returns the one
333    /// already submitted under `id`: a request is created once, so every replica and every
334    /// retry reaches the same record.
335    async fn submit(
336        &self,
337        id: String,
338        tool: &str,
339        args: Value,
340        summary: String,
341        policy: ApprovalPolicy,
342        requester: SubjectRef,
343    ) -> Result<adk_core::ApprovalRequest> {
344        let owner = match self.governing().await? {
345            Some(governance) => governance.holders(Role::Owner).next().map(str::to_string),
346            None => None,
347        };
348        let scope = ApprovalScope::new(
349            self.site.name.clone(),
350            owner.unwrap_or_else(|| "owner".to_string()),
351            APPROVAL_SESSION,
352        );
353        let call = ToolConfirmationRequest::new(tool, args);
354        let request = adk_core::ApprovalRequest::new(id, scope, &call, policy)
355            .with_summary(summary)
356            .with_requester(requester)
357            .with_allowed_actions([ApprovalAction::Approve, ApprovalAction::Reject]);
358        self.service.submit(request).await
359    }
360
361    /// The governance of the charter in force, when the runtime knows the charters.
362    async fn governing(&self) -> Result<Option<Governance>> {
363        let Some(charters) = &self.charters else { return Ok(None) };
364        let current = charters.current(self.site.id).await.map_err(kernel_error)?;
365        Ok(current.map(|version| version.charter.governance))
366    }
367}
368
369/// Refuses `by` when it is an agent: no agent approves, signs or holds a role (spec 3.5
370/// §7.6, A-I23).
371fn refuse_agent(by: &SubjectRef) -> Result<()> {
372    if super::is_agent(by) {
373        return Err(AdkError::new(
374            ErrorComponent::Tool,
375            ErrorCategory::Forbidden,
376            "website.approval.refused",
377            format!("{} is not a person, and no agent holds a role (spec 3.5 A-I23)", by.id),
378        ));
379    }
380    Ok(())
381}
382
383/// The subject of `principal`: an agent for an agent identity, a person otherwise.
384fn subject_of(principal: &str) -> SubjectRef {
385    if adk_kernel::charter::is_agent_principal(principal) {
386        SubjectRef::new(adk_core::principal::SubjectKind::Agent, principal)
387    } else {
388        SubjectRef::human(principal)
389    }
390}
391
392/// The people who fill `request`'s slots, each with the role their slot names.
393fn role_approvals(request: &adk_core::ApprovalRequest) -> Vec<RoleApproval> {
394    request
395        .slot_holders()
396        .into_iter()
397        .filter_map(|(slot, holder)| {
398            let ApproverSelector::Group(group) = slot else { return None };
399            let decision = holder?;
400            Some(RoleApproval::new(
401                group_role(group)?,
402                decision.authority().clone(),
403                decision.decided_at,
404            ))
405        })
406        .collect()
407}
408
409#[async_trait]
410impl ApprovalGate for SiteApprovals {
411    async fn decide(&self, request: &ApprovalRequest) -> adk_site::Result<ApprovalDecision> {
412        let pipeline = |error: AdkError| adk_site::SiteError::Pipeline(error.to_string());
413        let action = awp_types::ActionClass::from(request.action_class.as_str());
414        let governance = self.governing().await.map_err(pipeline)?.filter(|governance| {
415            governance.approval_chains.iter().any(|chain| chain.action == action)
416        });
417        let Some(governance) = governance else {
418            return Ok(ApprovalDecision::Approved {
419                approvers: vec![GOVERNED_APPROVER.to_string()],
420                decision: None,
421            });
422        };
423        let fingerprint = ReleaseFingerprint::new(self.site.id, &request.change);
424        let id = fingerprint.request_id(self.site.id);
425        let items: Vec<&str> = request.items.iter().map(|item| item.0.as_str()).collect();
426        let summary = match items.as_slice() {
427            [one] => format!("Publish {one}"),
428            many => format!("Publish {} items", many.len()),
429        };
430        let args = json!({
431            "site": self.site.id,
432            "actionClass": request.action_class,
433            "proposer": request.proposer,
434            "items": items,
435            "fingerprint": fingerprint.as_str(),
436            "diff": request.diff,
437        });
438        let stored = self
439            .submit(
440                id.clone(),
441                SITE_RELEASE_TOOL,
442                args,
443                summary,
444                chain_policy(&governance, &action),
445                subject_of(&request.proposer),
446            )
447            .await
448            .map_err(pipeline)?;
449        Ok(match stored.state {
450            ApprovalState::Pending => {
451                tracing::info!(website.release.request = %id, website.release.open_slots = stored.open_slots().len(), "release waits for its approval chain");
452                ApprovalDecision::Pending { ticket: id }
453            }
454            ApprovalState::Approved => ApprovalDecision::Approved {
455                approvers: role_approvals(&stored)
456                    .into_iter()
457                    .map(|approval| approval.principal.id)
458                    .collect(),
459                decision: Some(id),
460            },
461            ApprovalState::Rejected | ApprovalState::Responded => {
462                let last = stored.decisions.last();
463                ApprovalDecision::Rejected {
464                    by: last.map_or_else(String::new, |decision| decision.approver.id.clone()),
465                    reason: last.and_then(|decision| decision.reason.clone()).unwrap_or_default(),
466                }
467            }
468            ApprovalState::Expired | ApprovalState::Cancelled => ApprovalDecision::Rejected {
469                by: "approval-service".to_string(),
470                reason: stored
471                    .note
472                    .clone()
473                    .unwrap_or_else(|| format!("the request {}", stored.state.as_str())),
474            },
475        })
476    }
477}
478
479/// A charter signing request (spec 3.5 §7.6, §7.18 stage 5, A-I23): an approval request
480/// with one slot per role of the charter-change chain, committed only when distinct people
481/// fill every slot. Read from the approval service with [`SiteRuntime::charter_requests`];
482/// a record of this shape in the draft store is converted by
483/// [`SiteRuntime::restore_drafts`].
484#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
485#[serde(rename_all = "camelCase")]
486pub struct CharterSignRequest {
487    /// The request's id.
488    pub id: String,
489    /// The draft to commit.
490    pub draft: Charter,
491    /// The roles that must sign, one distinct person each.
492    pub roles: Vec<Role>,
493    /// The signatures so far.
494    pub signatures: Vec<RoleApproval>,
495    /// Who asked: the agent that drafted it.
496    pub requested_by: String,
497    /// When.
498    pub requested_at: DateTime<Utc>,
499    /// The committed version, once every signer signed.
500    #[serde(default, skip_serializing_if = "Option::is_none")]
501    pub committed: Option<u32>,
502    /// The approval request's version, the compare-and-swap token for the next signature.
503    #[serde(default)]
504    pub version: u64,
505}
506
507impl CharterSignRequest {
508    /// The view of the approval request `request`.
509    fn of(request: &adk_core::ApprovalRequest) -> Result<Self> {
510        let draft: Charter =
511            read(request.args_redacted.get("charter").cloned().unwrap_or_default())?;
512        Ok(Self {
513            id: request.id.clone(),
514            draft,
515            roles: request
516                .policy
517                .slots
518                .iter()
519                .filter_map(|slot| match slot {
520                    ApproverSelector::Group(group) => group_role(group),
521                    ApproverSelector::Subject(_) => None,
522                })
523                .collect(),
524            signatures: role_approvals(request),
525            requested_by: request.requester.as_ref().map(|r| r.id.clone()).unwrap_or_default(),
526            requested_at: request.created_at,
527            committed: None,
528            version: request.version,
529        })
530    }
531}
532
533/// A request that the owner promote a job (spec 3.5 §7.11, A-I13): the weekly review's
534/// offer, an approval request decided only by an owner. Read from the approval service with
535/// [`SiteRuntime::promotion_requests`].
536#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
537#[serde(rename_all = "camelCase")]
538pub struct PromotionRequest {
539    /// The request's id.
540    pub id: String,
541    /// The job.
542    pub job: String,
543    /// Why the agent asks: the evidence behind the offer.
544    pub reason: String,
545    /// Who asked.
546    pub requested_by: String,
547    /// When.
548    pub requested_at: DateTime<Utc>,
549    /// The approval request's version.
550    #[serde(default)]
551    pub version: u64,
552}
553
554impl PromotionRequest {
555    /// The view of the approval request `request`.
556    fn of(request: &adk_core::ApprovalRequest) -> Self {
557        let text = |key: &str| {
558            request.args_redacted.get(key).and_then(Value::as_str).unwrap_or_default().to_string()
559        };
560        Self {
561            id: request.id.clone(),
562            job: text("job"),
563            reason: text("reason"),
564            requested_by: request.requester.as_ref().map(|r| r.id.clone()).unwrap_or_default(),
565            requested_at: request.created_at,
566            version: request.version,
567        }
568    }
569}
570
571/// Everything the back-office tools act on (spec 3.5 §7.8, §7.8.2): build one with
572/// [`SiteRuntime::builder`].
573pub struct SiteRuntime {
574    pub(crate) site: SiteRef,
575    pub(crate) base: SiteProject,
576    pub(crate) store: Arc<dyn ContentStore>,
577    pub(crate) generator: Arc<dyn SiteGenerator>,
578    pub(crate) host: Arc<dyn SiteHost>,
579    pub(crate) pipeline: Arc<PublishingPipeline>,
580    pub(crate) gate: LaunchGate,
581    pub(crate) quarantine: Quarantine,
582    pub(crate) media: MediaPipeline,
583    pub(crate) work: PathBuf,
584    pub(crate) approvals: Arc<SiteApprovals>,
585    pub(crate) charters: Option<Arc<dyn CharterStore>>,
586    pub(crate) facts: Option<(Arc<dyn FactStore>, FactScope)>,
587    pub(crate) verifier: Option<Arc<dyn super::verify::SiteVerifier>>,
588    pub(crate) crawler: Option<Arc<dyn crate::web::RequestSigner>>,
589    pub(crate) audit: Option<adk_core::audit_log::AuditTrail>,
590    pub(crate) clock: Arc<dyn Clock>,
591    /// The previews this process staged, by draft id, with the draft version each shows.
592    pub(crate) previews: Mutex<BTreeMap<String, (u64, Preview)>>,
593    /// Held across a release's preview, approval and completion in this process.
594    pub(crate) publishing: Mutex<()>,
595    pub(crate) draft_store: Arc<dyn SiteDraftStore>,
596    pub(crate) governance: Option<GovernanceControl>,
597}
598
599impl std::fmt::Debug for SiteRuntime {
600    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
601        f.debug_struct("SiteRuntime").field("site", &self.site).finish_non_exhaustive()
602    }
603}
604
605/// Builds a [`SiteRuntime`].
606pub struct SiteRuntimeBuilder {
607    site: SiteRef,
608    base: SiteProject,
609    store: Arc<dyn ContentStore>,
610    generator: Arc<dyn SiteGenerator>,
611    host: Arc<dyn SiteHost>,
612    log: Arc<SiteLog>,
613    work: PathBuf,
614    history: Option<Arc<dyn ContentHistory>>,
615    announcer: Option<Arc<dyn Announcer>>,
616    tags: Option<Arc<dyn ChangeTagSink>>,
617    previous: Option<PreviousRelease>,
618    quarantine: Quarantine,
619    media: MediaPipeline,
620    charters: Option<Arc<dyn CharterStore>>,
621    facts: Option<(Arc<dyn FactStore>, FactScope)>,
622    verifier: Option<Arc<dyn super::verify::SiteVerifier>>,
623    crawler: Option<Arc<dyn crate::web::RequestSigner>>,
624    audit: Option<adk_core::audit_log::AuditTrail>,
625    clock: Arc<dyn Clock>,
626    gate: LaunchGate,
627    draft_store: Option<Arc<dyn SiteDraftStore>>,
628    approvals: Option<Arc<dyn ApprovalService>>,
629    governance: Option<GovernanceControl>,
630    require_durable: bool,
631}
632
633impl SiteRuntimeBuilder {
634    /// Keeps the site's decisions — release chains, charter signatures, job promotions — as
635    /// requests in `service` (spec 3.5 §7.8.2 step 4, A-I23), such as the kernel's, so the
636    /// back office, the web desk, the kernel's inbox and chat cards decide one record. The
637    /// service must take its groups from a
638    /// [`CharterDirectory`](adk_kernel::charter::CharterDirectory) for this site, so only the
639    /// people the charter names fill a chain's roles.
640    ///
641    /// Without one the runtime keeps them in a [`StoreApprovalService`] in memory, with the
642    /// directory, the runtime's clock and its audit trail.
643    ///
644    /// # Example
645    ///
646    /// ```rust,ignore
647    /// let service = StoreApprovalService::new(Arc::new(approval_store))
648    ///     .with_directory(Arc::new(CharterDirectory::new(charters.clone())))
649    ///     .with_audit(trail.clone());
650    /// let runtime = SiteRuntime::builder(site, base, store, generator, host, log, work)
651    ///     .charters(charters)
652    ///     .approvals(Arc::new(service))
653    ///     .build()?;
654    /// ```
655    #[must_use]
656    pub fn approvals(mut self, service: Arc<dyn ApprovalService>) -> Self {
657        self.approvals = Some(service);
658        self
659    }
660
661    /// Holds publishing while `control` is frozen (spec 3.5 §7.8.2, D5): a release whose
662    /// approval chain is satisfied — by the back office or by a person in the desk — waits
663    /// until the freeze lifts. Decisions are still recorded while frozen.
664    #[must_use]
665    pub fn governance(mut self, control: GovernanceControl) -> Self {
666        self.governance = Some(control);
667        self
668    }
669
670    /// Refuses to build with a store the runtime would keep in memory: the draft store and
671    /// the approval service must be set, as a served site's are (spec 3.5 §7.8.2 step 1).
672    #[must_use]
673    pub fn require_durable(mut self) -> Self {
674        self.require_durable = true;
675        self
676    }
677
678    /// Keeps the back office's drafts — content drafts, charter drafts, charter signing and
679    /// promotion requests — in `store`, so they survive a restart and every runtime over the
680    /// store sees the same ones (spec 3.5 §7.8.2 step 1); an [`InMemorySiteDraftStore`] by
681    /// default. The runtime reads the store at every call and writes it with a
682    /// compare-and-swap, so two runtimes editing one draft never overwrite each other.
683    ///
684    /// # Example
685    ///
686    /// ```rust,ignore
687    /// let runtime = SiteRuntime::builder(site, base, store, generator, host, log, work)
688    ///     .drafts(Arc::new(InMemorySiteDraftStore::default()))
689    ///     .build()?;
690    /// runtime.restore_drafts().await?;
691    /// ```
692    #[must_use]
693    pub fn drafts(mut self, store: Arc<dyn SiteDraftStore>) -> Self {
694        self.draft_store = Some(store);
695        self
696    }
697
698    /// Records every saved version, which per-item reverts need.
699    #[must_use]
700    pub fn history(mut self, history: Arc<dyn ContentHistory>) -> Self {
701        self.history = Some(history);
702        self
703    }
704
705    /// Announces releases.
706    #[must_use]
707    pub fn announcer(mut self, announcer: Arc<dyn Announcer>) -> Self {
708        self.announcer = Some(announcer);
709        self
710    }
711
712    /// Tags releases in the KPI history.
713    #[must_use]
714    pub fn tags(mut self, tags: Arc<dyn ChangeTagSink>) -> Self {
715        self.tags = Some(tags);
716        self
717    }
718
719    /// Continues after the release the host serves.
720    #[must_use]
721    pub fn previous(mut self, previous: PreviousRelease) -> Self {
722        self.previous = Some(previous);
723        self
724    }
725
726    /// The sanitiser's quarantine.
727    #[must_use]
728    pub fn quarantine(mut self, quarantine: Quarantine) -> Self {
729        self.quarantine = quarantine;
730        self
731    }
732
733    /// The media pipeline (default policy otherwise).
734    #[must_use]
735    pub fn media(mut self, media: MediaPipeline) -> Self {
736        self.media = media;
737        self
738    }
739
740    /// The charter store: approval chains, charter drafts and their commits.
741    #[must_use]
742    pub fn charters(mut self, charters: Arc<dyn CharterStore>) -> Self {
743        self.charters = Some(charters);
744        self
745    }
746
747    /// The site's long-term facts in `scope`: claims are checked against them (A-I18) and
748    /// discovery and interview answers are recorded in them.
749    #[must_use]
750    pub fn facts(mut self, facts: Arc<dyn FactStore>, scope: FactScope) -> Self {
751        self.facts = Some((facts, scope));
752        self
753    }
754
755    /// The verifier `awp_verify` runs.
756    #[must_use]
757    pub fn verifier(mut self, verifier: Arc<dyn super::verify::SiteVerifier>) -> Self {
758        self.verifier = Some(verifier);
759        self
760    }
761
762    /// Signs the crawls `site_discover` makes (spec 3.5 §7.3 "Outbound").
763    #[must_use]
764    pub fn crawler_signer(mut self, signer: Arc<dyn crate::web::RequestSigner>) -> Self {
765        self.crawler = Some(signer);
766        self
767    }
768
769    /// Where the `website.*` records go, with the pipeline's `site.content.*` and
770    /// `site.release.*` records (spec 3.5 §9.3).
771    #[must_use]
772    pub fn audit(mut self, trail: adk_core::audit_log::AuditTrail) -> Self {
773        self.audit = Some(trail);
774        self
775    }
776
777    /// The clock.
778    #[must_use]
779    pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
780        self.clock = clock;
781        self
782    }
783
784    /// A launch gate with red lines or extensions; the claim check over the site's facts is
785    /// added to it.
786    #[must_use]
787    pub fn gate(mut self, gate: LaunchGate) -> Self {
788        self.gate = gate;
789        self
790    }
791
792    /// The runtime.
793    ///
794    /// # Errors
795    ///
796    /// `website.runtime.not_durable` under [`require_durable`](Self::require_durable) when
797    /// the draft store or the approval service is not set.
798    pub fn build(self) -> Result<Arc<SiteRuntime>> {
799        if self.require_durable {
800            let held: Vec<&str> = [
801                (self.draft_store.is_none(), "drafts (SiteRuntimeBuilder::drafts)"),
802                (self.approvals.is_none(), "approvals (SiteRuntimeBuilder::approvals)"),
803            ]
804            .into_iter()
805            .filter_map(|(missing, store)| missing.then_some(store))
806            .collect();
807            if !held.is_empty() {
808                return Err(AdkError::new(
809                    ErrorComponent::Tool,
810                    ErrorCategory::InvalidInput,
811                    "website.runtime.not_durable",
812                    format!(
813                        "the site runtime would keep {} in memory, and a restart would lose \
814                         them; set a SQLite, PostgreSQL or Redis store for each",
815                        held.join(" and ")
816                    ),
817                ));
818            }
819        }
820        let service = match self.approvals {
821            Some(service) => service,
822            None => {
823                let mut service = StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()))
824                    .with_clock(self.clock.clone());
825                if let Some(charters) = &self.charters {
826                    let directory = CharterDirectory::new(charters.clone()).for_site(self.site.id);
827                    service = service.with_directory(Arc::new(directory));
828                }
829                if let Some(trail) = &self.audit {
830                    service = service.with_audit(trail.clone());
831                }
832                Arc::new(service) as Arc<dyn ApprovalService>
833            }
834        };
835        let approvals = Arc::new(SiteApprovals {
836            site: self.site.clone(),
837            charters: self.charters.clone(),
838            service,
839        });
840        let gate = match &self.facts {
841            Some((facts, scope)) => self
842                .gate
843                .with_claim_check(Arc::new(FactClaimCheck::new(facts.clone(), scope.clone()))),
844            None => self.gate,
845        };
846        let mut pipeline = PublishingPipeline::builder(
847            self.base.clone(),
848            self.store.clone(),
849            self.generator.clone(),
850            self.host.clone(),
851            self.log,
852            self.work.join("pipeline"),
853        )
854        .gate(gate.clone())
855        .approvals(approvals.clone())
856        .quarantine(self.quarantine.clone())
857        .clock(self.clock.clone());
858        if let Some(history) = self.history {
859            pipeline = pipeline.history(history);
860        }
861        if let Some(announcer) = self.announcer {
862            pipeline = pipeline.announcer(announcer);
863        }
864        if let Some(tags) = self.tags {
865            pipeline = pipeline.tags(tags);
866        }
867        if let Some(previous) = self.previous {
868            pipeline = pipeline.previous(previous);
869        }
870        // The pipeline writes the `site.content.*` and `site.release.*` records (spec 3.5 §9.3).
871        if let Some(trail) = &self.audit {
872            pipeline = pipeline.audit(trail.clone());
873        }
874        Ok(Arc::new(SiteRuntime {
875            site: self.site,
876            base: self.base,
877            store: self.store,
878            generator: self.generator,
879            host: self.host,
880            pipeline: Arc::new(pipeline.build()),
881            gate,
882            quarantine: self.quarantine,
883            media: self.media,
884            work: self.work,
885            approvals,
886            charters: self.charters,
887            facts: self.facts,
888            verifier: self.verifier,
889            crawler: self.crawler,
890            audit: self.audit,
891            clock: self.clock,
892            previews: Mutex::new(BTreeMap::new()),
893            publishing: Mutex::new(()),
894            draft_store: self
895                .draft_store
896                .unwrap_or_else(|| Arc::new(InMemorySiteDraftStore::default())),
897            governance: self.governance,
898        }))
899    }
900}
901
902impl SiteRuntime {
903    /// A runtime for `site` over `adk-site`'s parts: `base` carries the configuration,
904    /// theme, terms and capabilities; items come from `store`; `work` holds builds.
905    ///
906    /// # Example
907    ///
908    /// ```rust,ignore
909    /// let runtime = SiteRuntime::builder(site, base, store, Arc::new(BuiltinGenerator), host, log, work)
910    ///     .charters(charters)
911    ///     .facts(facts, scope)
912    ///     .build()?;
913    /// ```
914    pub fn builder(
915        site: SiteRef,
916        base: SiteProject,
917        store: Arc<dyn ContentStore>,
918        generator: Arc<dyn SiteGenerator>,
919        host: Arc<dyn SiteHost>,
920        log: Arc<SiteLog>,
921        work: impl Into<PathBuf>,
922    ) -> SiteRuntimeBuilder {
923        SiteRuntimeBuilder {
924            site,
925            base,
926            store,
927            generator,
928            host,
929            log,
930            work: work.into(),
931            history: None,
932            announcer: None,
933            tags: None,
934            previous: None,
935            quarantine: Quarantine::default(),
936            media: MediaPipeline::default(),
937            charters: None,
938            facts: None,
939            verifier: None,
940            crawler: None,
941            audit: None,
942            clock: Arc::new(SystemClock),
943            gate: LaunchGate::new(),
944            draft_store: None,
945            approvals: None,
946            governance: None,
947            require_durable: false,
948        }
949    }
950
951    /// The site.
952    pub fn site(&self) -> &SiteRef {
953        &self.site
954    }
955
956    /// The publishing pipeline.
957    pub fn pipeline(&self) -> &PublishingPipeline {
958        &self.pipeline
959    }
960
961    /// The publishing pipeline, shared: an `adk-site` `UpdateEngine` publishes through it,
962    /// so its batches and the back office's releases follow one another (spec 3.5 §7.8.3).
963    pub fn shared_pipeline(&self) -> Arc<PublishingPipeline> {
964        Arc::clone(&self.pipeline)
965    }
966
967    /// The content store.
968    pub fn store(&self) -> &Arc<dyn ContentStore> {
969        &self.store
970    }
971
972    /// The host.
973    pub fn host(&self) -> &Arc<dyn SiteHost> {
974        &self.host
975    }
976
977    /// The release approval gate, where people record their approvals under a chain.
978    pub fn approvals(&self) -> &Arc<SiteApprovals> {
979        &self.approvals
980    }
981
982    /// The newest content draft that entered through `entry`, with its id and its items
983    /// (spec 3.5 §7.8.2 "Entry points", §5 S18): the draft a paired person's turn made, which
984    /// the photos their message carried join. `None` when that entry has no draft waiting or
985    /// the draft store cannot be read.
986    ///
987    /// # Example
988    ///
989    /// ```rust,no_run
990    /// use adk_site::pipeline::EntryPoint;
991    ///
992    /// # async fn example(runtime: &adk_harness::website::SiteRuntime) {
993    /// let device = EntryPoint::PairedDevice { device: "ch-5c1e09a2d4b7f3e".into() };
994    /// if let Some((draft, items)) = runtime.newest_draft_from(&device).await {
995    ///     println!("{draft} drafts {}", items[0].id.0);
996    /// }
997    /// # }
998    /// ```
999    pub async fn newest_draft_from(
1000        &self,
1001        entry: &EntryPoint,
1002    ) -> Option<(String, Vec<awp_types::ContentItem>)> {
1003        let records = match self.draft_store.list(self.site.id, DraftKind::Content).await {
1004            Ok(records) => records,
1005            Err(error) => {
1006                tracing::warn!(website.site = %self.site.name, error = %error, "the draft store cannot be read");
1007                return None;
1008            }
1009        };
1010        // The store lists in creation order, so the last match is the newest.
1011        records.into_iter().rev().find_map(|record| {
1012            let draft = read::<StoredDraft>(record.value).ok()?;
1013            (draft.entry == *entry).then_some((record.id, draft.items))
1014        })
1015    }
1016
1017    /// Whether the site has been launched: a production release is logged or served
1018    /// (spec 3.5 A-I21).
1019    pub async fn launched(&self) -> bool {
1020        if self.pipeline.previous().await.is_some() {
1021            return true;
1022        }
1023        matches!(self.host.fetch(CHECKPOINT_PATH).await, Ok(Some(_)))
1024    }
1025
1026    /// Checks that the drafts the runtime's draft store holds for the site — content drafts
1027    /// and charter drafts — read back, and converts the charter signing and promotion
1028    /// requests an earlier version kept there into requests in the approval service
1029    /// (spec 3.5 §7.8.2 step 1, A-I23). Each becomes the request
1030    /// `site-charter-{site}-legacy-{id}` or `site-promotion-{site}-legacy-{id}`, keeps the
1031    /// signatures of people who still hold their role, and leaves the draft store; a request
1032    /// its signatures already satisfy is committed. A second run converts nothing twice. The
1033    /// runtime reads the store at every call, so nothing is copied into memory. Returns how
1034    /// many drafts and requests the store held.
1035    ///
1036    /// # Errors
1037    ///
1038    /// The draft store's or the approval service's error, or a stored record that does not
1039    /// read back.
1040    pub async fn restore_drafts(&self) -> Result<usize> {
1041        let site = self.site.id;
1042        let mut held = 0;
1043        for record in self.draft_store.list(site, DraftKind::Content).await? {
1044            read::<StoredDraft>(record.value)?.into_draft()?;
1045            held += 1;
1046        }
1047        for record in self.draft_store.list(site, DraftKind::Charter).await? {
1048            read::<Charter>(record.value)?;
1049            held += 1;
1050        }
1051        for record in self.draft_store.list(site, DraftKind::CharterSign).await? {
1052            let legacy: CharterSignRequest = read(record.value)?;
1053            if legacy.committed.is_none() {
1054                let id = format!("site-charter-{site}-legacy-{}", record.id);
1055                let mut request = self
1056                    .submit_charter_signing(id, None, legacy.draft, &legacy.requested_by)
1057                    .await?;
1058                for signature in legacy.signatures {
1059                    match self
1060                        .approvals
1061                        .approve(&request.id, request.version, &signature.principal)
1062                        .await
1063                    {
1064                        Ok(after) => request = after,
1065                        Err(error) => {
1066                            tracing::info!(website.request = %request.id, error = %error, "a signature that no longer counts was not carried over");
1067                        }
1068                    }
1069                }
1070                if request.state == ApprovalState::Approved {
1071                    self.commit_signed(&request).await?;
1072                }
1073            }
1074            self.draft_store.remove(site, DraftKind::CharterSign, &record.id).await?;
1075            held += 1;
1076        }
1077        for record in self.draft_store.list(site, DraftKind::Promotion).await? {
1078            let legacy: PromotionRequest = read(record.value)?;
1079            let id = format!("site-promotion-{site}-legacy-{}", record.id);
1080            self.submit_promotion(id, &legacy.job, &legacy.reason, &legacy.requested_by).await?;
1081            self.draft_store.remove(site, DraftKind::Promotion, &record.id).await?;
1082            held += 1;
1083        }
1084        if held > 0 {
1085            tracing::info!(website.site = %self.site.name, website.drafts.held = held, "drafts held in the draft store");
1086        }
1087        Ok(held)
1088    }
1089
1090    /// Keeps `value` as a new record of `kind` under an id the store allocates.
1091    pub(crate) async fn create(
1092        &self,
1093        kind: DraftKind,
1094        value: &impl Serialize,
1095    ) -> Result<StoredRecord> {
1096        let value = serde_json::to_value(value).map_err(store_error)?;
1097        self.draft_store.create(self.site.id, kind, &value).await
1098    }
1099
1100    /// The record `id` of `kind` and the version it was read at.
1101    pub(crate) async fn record<T: serde::de::DeserializeOwned>(
1102        &self,
1103        kind: DraftKind,
1104        id: &str,
1105    ) -> Result<Option<(u64, T)>> {
1106        match self.draft_store.get(self.site.id, kind, id).await? {
1107            Some(record) => Ok(Some((record.version, read(record.value)?))),
1108            None => Ok(None),
1109        }
1110    }
1111
1112    /// Writes `value` over the record `id` of `kind` read at `version`.
1113    ///
1114    /// # Errors
1115    ///
1116    /// `website.drafts.conflict` when the record changed or was removed since it was read.
1117    pub(crate) async fn replace(
1118        &self,
1119        kind: DraftKind,
1120        id: &str,
1121        version: u64,
1122        value: &impl Serialize,
1123    ) -> Result<()> {
1124        let value = serde_json::to_value(value).map_err(store_error)?;
1125        if self.draft_store.replace(self.site.id, kind, id, &value, version).await? {
1126            Ok(())
1127        } else {
1128            Err(conflict(kind, id))
1129        }
1130    }
1131
1132    /// The content draft `id` and the version it was read at.
1133    pub(crate) async fn content_draft(&self, id: &str) -> Result<Option<(u64, Draft)>> {
1134        match self.record::<StoredDraft>(DraftKind::Content, id).await? {
1135            Some((version, stored)) => Ok(Some((version, stored.into_draft()?))),
1136            None => Ok(None),
1137        }
1138    }
1139
1140    /// Writes `draft` over the content draft `id` read at `version`; its preview no longer
1141    /// shows it.
1142    ///
1143    /// # Errors
1144    ///
1145    /// `website.drafts.conflict` when the draft changed or was removed since it was read.
1146    pub(crate) async fn replace_draft(&self, id: &str, version: u64, draft: &Draft) -> Result<()> {
1147        self.previews.lock().await.remove(id);
1148        self.replace(DraftKind::Content, id, version, &StoredDraft::of(draft)).await
1149    }
1150
1151    /// Forgets the content draft `id`: it was published or refused. A failure is logged; the
1152    /// release stands.
1153    pub(crate) async fn forget_draft(&self, id: &str) {
1154        self.previews.lock().await.remove(id);
1155        if let Err(error) = self.draft_store.remove(self.site.id, DraftKind::Content, id).await {
1156            tracing::warn!(website.draft = id, error = %error, "a finished draft stays in the draft store");
1157        }
1158    }
1159
1160    /// Runs the launch gate's full tier over the working copy as it would publish now
1161    /// (spec 3.5 §7.8.1).
1162    ///
1163    /// # Errors
1164    ///
1165    /// Build and gate errors.
1166    pub async fn run_launch_gate(&self) -> Result<GateReport> {
1167        let mut project = self.base.clone();
1168        project.items = self.store.list().await.map_err(site_error)?;
1169        project.items.sort_by(|a, b| a.id.cmp(&b.id));
1170        for item in &project.items {
1171            for media in &item.media {
1172                if !project.media.contains_key(&media.path)
1173                    && let Some(bytes) =
1174                        self.store.read_media(&media.path).await.map_err(site_error)?
1175                {
1176                    project.media.insert(media.path.clone(), bytes);
1177                }
1178            }
1179        }
1180        project.as_of = self.clock.now();
1181        project.redirects_format = self.host.redirects_format();
1182        let out = self.work.join(format!("gate-{}", Uuid::new_v4()));
1183        let report = self.generator.build(&project, &out).await.map_err(site_error)?;
1184        let verdict = self
1185            .gate
1186            .run(
1187                GateMode::Full,
1188                &GateInput {
1189                    project: &project,
1190                    out: &out,
1191                    report: &report,
1192                    changed: None,
1193                    quarantine: &self.quarantine,
1194                },
1195            )
1196            .await
1197            .map_err(site_error);
1198        let _ = tokio::fs::remove_dir_all(&out).await;
1199        verdict
1200    }
1201
1202    /// Whether publishing is held: the runtime's governance control is frozen (spec 3.5
1203    /// §7.8.2, D5). A release whose chain is satisfied waits until the freeze lifts.
1204    pub fn is_frozen(&self) -> bool {
1205        self.governance.as_ref().is_some_and(GovernanceControl::is_frozen)
1206    }
1207
1208    /// Asks every required signer to sign the charter draft `draft` the back office keeps
1209    /// (spec 3.5 §7.6, §7.18 stage 5, A-I23), as [`request_charter`](Self::request_charter)
1210    /// does for its content.
1211    ///
1212    /// # Errors
1213    ///
1214    /// `website.charter.draft_not_found` for an unknown draft; as
1215    /// [`request_charter`](Self::request_charter).
1216    pub async fn request_charter_signing(
1217        &self,
1218        draft: &str,
1219        requested_by: &str,
1220    ) -> Result<adk_core::ApprovalRequest> {
1221        let (_, charter) =
1222            self.record::<Charter>(DraftKind::Charter, draft).await?.ok_or_else(|| {
1223                AdkError::new(
1224                    ErrorComponent::Tool,
1225                    ErrorCategory::InvalidInput,
1226                    "website.charter.draft_not_found",
1227                    format!("no charter draft '{draft}'"),
1228                )
1229            })?;
1230        self.request_charter(&charter, Some(draft), requested_by).await
1231    }
1232
1233    /// Asks every required signer to sign `charter` as the site's next version (spec 3.5
1234    /// §7.6, §7.18 stage 5, A-I23): one approval request per content and version in force,
1235    /// with a slot for each role of the charter-change chain of the charter in force — or of
1236    /// `charter`, for a site's first. The back office and the web desk asking for the same
1237    /// content reach the same request; an edit gets a new one, so earlier signatures stop
1238    /// counting.
1239    ///
1240    /// # Errors
1241    ///
1242    /// `website.charter.invalid` for a charter that fails `Charter::validate()`; the stores'
1243    /// errors.
1244    pub async fn request_charter(
1245        &self,
1246        charter: &Charter,
1247        draft: Option<&str>,
1248        requested_by: &str,
1249    ) -> Result<adk_core::ApprovalRequest> {
1250        if let Err(error) = charter.validate() {
1251            return Err(AdkError::new(
1252                ErrorComponent::Tool,
1253                ErrorCategory::InvalidInput,
1254                "website.charter.invalid",
1255                format!("the draft cannot be committed: {error}"),
1256            ));
1257        }
1258        let id = self.charter_request_id(charter).await?;
1259        self.submit_charter_signing(id, draft, charter.clone(), requested_by).await
1260    }
1261
1262    /// The signing request for `charter`, when one was asked for, with the version it
1263    /// committed.
1264    ///
1265    /// # Errors
1266    ///
1267    /// The stores' errors.
1268    pub async fn charter_request(&self, charter: &Charter) -> Result<Option<CharterSignRequest>> {
1269        let id = self.charter_request_id(charter).await?;
1270        let Some(request) = self.approvals.get(&id).await? else { return Ok(None) };
1271        let mut view = CharterSignRequest::of(&request)?;
1272        if let Some(charters) = &self.charters {
1273            view.committed = charters
1274                .history(self.site.id)
1275                .await
1276                .map_err(kernel_error)?
1277                .iter()
1278                .find(|version| version.decision.decision_id == id)
1279                .map(CharterVersion::version);
1280        }
1281        Ok(Some(view))
1282    }
1283
1284    /// The id of the signing request for `charter` as the next version:
1285    /// `site-charter-{site}-v{next}-{first 16 hex digits of the content's digest}`.
1286    async fn charter_request_id(&self, charter: &Charter) -> Result<String> {
1287        let next = match &self.charters {
1288            Some(charters) => charters
1289                .current(self.site.id)
1290                .await
1291                .map_err(kernel_error)?
1292                .map_or(1, |current| current.version() + 1),
1293            None => 1,
1294        };
1295        let content = serde_json::to_vec(charter).map_err(store_error)?;
1296        let digest = adk_site::release::file_digest(&content).to_string();
1297        let hex = digest.trim_start_matches("sha256:");
1298        Ok(format!("site-charter-{}-v{next}-{}", self.site.id, &hex[..16.min(hex.len())]))
1299    }
1300
1301    /// Submits the charter signing request `id` for `charter`.
1302    async fn submit_charter_signing(
1303        &self,
1304        id: String,
1305        draft: Option<&str>,
1306        charter: Charter,
1307        requested_by: &str,
1308    ) -> Result<adk_core::ApprovalRequest> {
1309        let governing = match &self.charters {
1310            Some(charters) => charters
1311                .current(self.site.id)
1312                .await
1313                .map_err(kernel_error)?
1314                .map(|current| current.charter.governance),
1315            None => None,
1316        }
1317        .unwrap_or_else(|| charter.governance.clone());
1318        let summary = match &charter.mission {
1319            mission if mission.is_empty() => "Sign the charter".to_string(),
1320            mission => format!("Sign the charter: {mission}"),
1321        };
1322        let args = json!({ "site": self.site.id, "draft": draft, "charter": charter });
1323        self.approvals
1324            .submit(
1325                id,
1326                CHARTER_SIGN_TOOL,
1327                args,
1328                summary,
1329                chain_policy(&governing, &CHARTER_ACTION),
1330                subject_of(requested_by),
1331            )
1332            .await
1333    }
1334
1335    /// Asks the owner to promote `job` (spec 3.5 §7.11, A-I13): an approval request only an
1336    /// owner decides. While one waits for the job, asking again returns it.
1337    ///
1338    /// # Errors
1339    ///
1340    /// The approval service's error.
1341    pub async fn request_promotion(
1342        &self,
1343        job: &str,
1344        reason: &str,
1345        requested_by: &str,
1346    ) -> Result<adk_core::ApprovalRequest> {
1347        let waiting = self.approvals.list(JOB_PROMOTION_TOOL, &[ApprovalState::Pending]).await?;
1348        if let Some(open) = waiting
1349            .into_iter()
1350            .find(|request| request.args_redacted.get("job").and_then(Value::as_str) == Some(job))
1351        {
1352            return Ok(open);
1353        }
1354        let id = format!("site-promotion-{}-{}", self.site.id, Uuid::new_v4().simple());
1355        self.submit_promotion(id, job, reason, requested_by).await
1356    }
1357
1358    /// Submits the promotion request `id`.
1359    async fn submit_promotion(
1360        &self,
1361        id: String,
1362        job: &str,
1363        reason: &str,
1364        requested_by: &str,
1365    ) -> Result<adk_core::ApprovalRequest> {
1366        let owner = ApproverSelector::group(adk_kernel::charter::role_group(Role::Owner));
1367        self.approvals
1368            .submit(
1369                id,
1370                JOB_PROMOTION_TOOL,
1371                json!({ "site": self.site.id, "job": job, "reason": reason }),
1372                format!("Promote the {job} job: {reason}"),
1373                ApprovalPolicy::for_slots([owner]),
1374                subject_of(requested_by),
1375            )
1376            .await
1377    }
1378
1379    /// The charter signing requests that wait.
1380    pub async fn charter_requests(&self) -> Vec<CharterSignRequest> {
1381        match self.approvals.list(CHARTER_SIGN_TOOL, &[ApprovalState::Pending]).await {
1382            Ok(requests) => requests
1383                .iter()
1384                .filter_map(|request| match CharterSignRequest::of(request) {
1385                    Ok(view) => Some(view),
1386                    Err(error) => {
1387                        tracing::warn!(website.request = %request.id, error = %error, "a charter signing request does not read back");
1388                        None
1389                    }
1390                })
1391                .collect(),
1392            Err(error) => {
1393                tracing::warn!(website.site = %self.site.name, error = %error, "the approval service cannot be read");
1394                Vec::new()
1395            }
1396        }
1397    }
1398
1399    /// The promotion requests that wait for the owner.
1400    pub async fn promotion_requests(&self) -> Vec<PromotionRequest> {
1401        match self.approvals.list(JOB_PROMOTION_TOOL, &[ApprovalState::Pending]).await {
1402            Ok(requests) => requests.iter().map(PromotionRequest::of).collect(),
1403            Err(error) => {
1404                tracing::warn!(website.site = %self.site.name, error = %error, "the approval service cannot be read");
1405                Vec::new()
1406            }
1407        }
1408    }
1409
1410    /// Records `approval` — a person signing in a role — on the charter signing request
1411    /// `id`, and commits the draft through `commit_audited` once distinct people fill every
1412    /// role of the chain (spec 3.5 §7.6, A-I23). The commit's decision is the request. No
1413    /// agent signs, and the agent that asked never commits.
1414    ///
1415    /// # Errors
1416    ///
1417    /// `NotFound` for an unknown request; `Forbidden` for a signature no person made or in a
1418    /// role the signer does not hold; the approval service's errors, such as
1419    /// `approval.already_decided` for a second signature by one person; the stores' errors.
1420    pub async fn sign_charter(
1421        &self,
1422        id: &str,
1423        approval: RoleApproval,
1424    ) -> Result<Option<CharterVersion>> {
1425        if super::is_agent(&approval.principal) {
1426            return Err(AdkError::new(
1427                ErrorComponent::Tool,
1428                ErrorCategory::Forbidden,
1429                "website.charter.agent_signer",
1430                format!(
1431                    "{} is not a person: no agent signs a charter (spec 3.5 §7.6, A-I23)",
1432                    approval.principal.id
1433                ),
1434            ));
1435        }
1436        let charters = self.charters.as_ref().ok_or_else(|| {
1437            AdkError::config("signing a charter needs the site's charter store (spec 3.5 §7.6)")
1438        })?;
1439        let request = self
1440            .approvals
1441            .get(id)
1442            .await?
1443            .filter(|request| request.tool_name == CHARTER_SIGN_TOOL)
1444            .ok_or_else(|| {
1445                AdkError::new(
1446                    ErrorComponent::Tool,
1447                    ErrorCategory::NotFound,
1448                    "website.charter.request_not_found",
1449                    format!("no charter signing request '{id}'"),
1450                )
1451            })?;
1452        let governing = match charters.current(self.site.id).await.map_err(kernel_error)? {
1453            Some(current) => current.charter.governance,
1454            None => CharterSignRequest::of(&request)?.draft.governance,
1455        };
1456        if !governing.holds(&approval.principal.id, approval.role) {
1457            return Err(AdkError::new(
1458                ErrorComponent::Tool,
1459                ErrorCategory::Forbidden,
1460                "website.charter.not_a_signer",
1461                format!("{} does not hold the {:?} role", approval.principal.id, approval.role),
1462            ));
1463        }
1464        let signed = self.approvals.approve(id, request.version, &approval.principal).await?;
1465        if signed.state != ApprovalState::Approved {
1466            return Ok(None);
1467        }
1468        self.commit_signed(&signed).await
1469    }
1470
1471    /// Commits every charter whose signing request people approved on any surface — the
1472    /// desk, the kernel's inbox, a chat card — and that is not committed yet. Returns the
1473    /// versions committed now.
1474    ///
1475    /// # Errors
1476    ///
1477    /// The stores' errors.
1478    pub async fn settle_charters(&self) -> Result<Vec<CharterVersion>> {
1479        let mut committed = Vec::new();
1480        for request in self.approvals.list(CHARTER_SIGN_TOOL, &[ApprovalState::Approved]).await? {
1481            committed.extend(self.commit_signed(&request).await?);
1482        }
1483        Ok(committed)
1484    }
1485
1486    /// Commits the charter of the approved signing request `request`, its signers as the
1487    /// decision's approvals and the request as the decision; `None` when a version already
1488    /// carries that decision.
1489    async fn commit_signed(
1490        &self,
1491        request: &adk_core::ApprovalRequest,
1492    ) -> Result<Option<CharterVersion>> {
1493        let charters = self.charters.as_ref().ok_or_else(|| {
1494            AdkError::config("committing a charter needs the site's charter store (spec 3.5 §7.6)")
1495        })?;
1496        let committed = || async {
1497            let history = charters.history(self.site.id).await.map_err(kernel_error)?;
1498            Ok::<_, AdkError>(
1499                history.iter().any(|version| version.decision.decision_id == request.id),
1500            )
1501        };
1502        if committed().await? {
1503            return Ok(None);
1504        }
1505        let view = CharterSignRequest::of(request)?;
1506        let mut decision = CommitDecision::new(request.id.clone(), self.clock.now());
1507        for signature in view.signatures {
1508            decision = decision.with_approval(signature);
1509        }
1510        match commit_audited(charters.as_ref(), view.draft, decision, self.audit.as_ref()).await {
1511            Ok(version) => Ok(Some(version)),
1512            // Another replica committed the same decision first.
1513            Err(_) if committed().await? => Ok(None),
1514            Err(error) => Err(kernel_error(error)),
1515        }
1516    }
1517}
1518
1519/// Reads a stored record as `T`.
1520fn read<T: serde::de::DeserializeOwned>(value: Value) -> Result<T> {
1521    serde_json::from_value(value).map_err(store_error)
1522}