Skip to main content

adk_website/repository/
mod.rs

1//! Files and git as an entry point (spec 3.5 §7.8.2 "Entry points", A-I23, A-I24): a push
2//! from an authorised committer to the content repository arrives through a signed webhook
3//! and proposes a release, which waits at the site's normal approval.
4//!
5//! ```text
6//! forge ──signed push──▶ /hooks/{name} (adk-server's WebhookIngress, keyed by delivery id)
7//!   ──durable run──▶ the site's kernel ──REPOSITORY_WORKFLOW──▶ RepositoryEntry::receive
8//!   ──▶ a listed committer?
9//!         no  ──▶ one `inbound_message` signal; nothing is authored (A-I24)
10//!         yes ──▶ CommitSource reads the changed content files at the pushed commit
11//!             ──▶ the pipeline: draft, the per-change checks, the preview with page diffs
12//!             ──▶ the owner's decision card ──approved──▶ the approval chain (A-I23),
13//!                 release, publish, announce, measure
14//! ```
15//!
16//! | Part | Does |
17//! |---|---|
18//! | [`RepositoryConfig`] | `repository.json`: the branch, where files are read, the signed hooks and the authorised committers |
19//! | [`PushEvent`] | A push as GitHub, GitLab or the plain signed form describes it |
20//! | [`source`] | [`source::CommitSource`]: files read from the pushed commit; a local git repository or a forge's raw endpoint over HTTP |
21//! | [`RepositoryEntry`] | Authorises the pusher, drafts and previews the change, cards it for the owner, and applies the owner's decision |
22//!
23//! | Hook | Authenticated by | The committer is |
24//! |---|---|---|
25//! | `github` | `X-Hub-Signature-256` with the hook's secret | The listed `account` that pushed (`sender.login`, else `pusher.name`) |
26//! | `gitlab` | `X-Gitlab-Token` with the hook's secret | The listed `account` that pushed (`user_username`) |
27//! | `signed` | Standard Webhooks with the hook's `whsec_` key, from any host | The one committer whose `key` the hook is |
28//!
29//! A push is taken once: the ingress keys its run by the delivery id, and the entry keeps
30//! every commit it has taken in `data/repository/pushes.json`, so a delivery replayed under
31//! another id proposes nothing again; a commit only signalled stays open to a listed
32//! committer's push. Only the configured branch proposes releases, and only
33//! content files (`content/<kind>/<slug>/<language>.md`) are read; a removed one withdraws
34//! its item (410 Gone).
35
36pub mod source;
37
38use std::collections::BTreeMap;
39use std::path::{Path, PathBuf};
40use std::sync::Arc;
41use std::time::Duration;
42
43use adk_core::principal::SubjectRef;
44use adk_core::{
45    AdkError, ApprovalPolicy, ApprovalRequest, ApprovalRisk, ApprovalScope, ApprovalService,
46    ApprovalState, ApproverSelector, DurableRunStore, NewRun, Result, ToolConfirmationRequest,
47};
48use adk_harness::website::{SiteRef, SiteRuntime};
49use adk_kernel::QueueClass;
50use adk_server::awp::SignalEmitter;
51use adk_server::webhooks::{
52    ForgeSecret, ForgeSignature, WebhookHook, WebhookIngress, webhook_ingress_router,
53};
54use adk_site::content::{CONTENT_DIR, parse_content_file};
55use adk_site::pipeline::{ApprovalDecision, Change, Draft, EntryPoint, PipelineOutcome, Preview};
56use awp_types::{
57    Channel, ContentId, ContentItem, ContentState, MessageCategory, Signal, SignalKind, ThreadRef,
58};
59use chrono::{DateTime, Utc};
60use serde::{Deserialize, Serialize};
61use serde_json::{Value, json};
62use tokio::sync::Mutex;
63use tokio::task::JoinHandle;
64
65use self::source::{CommitSource, FileChange, HttpCommitSource, LocalGitSource, is_commit_id};
66use crate::deploy::project::{ProjectPaths, read_json, secret_in};
67
68/// The workflow a push's run executes in the site's kernel (spec 3.5 §7.8.2).
69pub const REPOSITORY_WORKFLOW: &str = "website.repository.push";
70/// The tool a push's decision card names.
71pub const REPOSITORY_RELEASE: &str = "site_repository_release";
72/// The job a push's release records as its source.
73pub const REPOSITORY_JOB: &str = "repository";
74/// The project file that configures the entry point.
75pub const REPOSITORY_FILE: &str = "repository.json";
76/// The most push records `data/repository/pushes.json` keeps.
77const KEPT_RECORDS: usize = 5_000;
78
79fn config(error: impl std::fmt::Display) -> AdkError {
80    AdkError::config(error.to_string())
81}
82
83fn default_branch() -> String {
84    "main".to_string()
85}
86
87/// How a hook's deliveries are signed (spec 3.5 §7.8.2).
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
89#[serde(rename_all = "snake_case")]
90pub enum Forge {
91    /// GitHub's push webhook, `X-Hub-Signature-256`.
92    Github,
93    /// GitLab's push webhook, `X-Gitlab-Token`.
94    Gitlab,
95    /// The plain signed form any host can send: Standard Webhooks over a [`PushEvent`]
96    /// document.
97    Signed,
98}
99
100/// One signed webhook, served at `/hooks/{name}` on the site's edge.
101#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
102#[serde(rename_all = "camelCase", deny_unknown_fields)]
103pub struct HookConfig {
104    /// The hook's name: letters, digits, `-` and `_`.
105    pub name: String,
106    /// How its deliveries are signed.
107    pub forge: Forge,
108    /// Its secret, as `env:VAR` or `file:PATH`: the forge's webhook secret, or a Standard
109    /// Webhooks `whsec_` key for `signed`.
110    pub secret: String,
111}
112
113/// An authorised committer: a forge account, or the key of a signed hook (spec 3.5 A-I24).
114#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
115#[serde(rename_all = "camelCase", deny_unknown_fields)]
116pub struct CommitterConfig {
117    /// The person, as the charter's governance names them: the proposer of the releases
118    /// their pushes make, who cannot also approve them under an approval chain (A-I23).
119    pub id: String,
120    /// A forge account, `{hook}:{username}`: that account's pushes on that hook.
121    #[serde(default, skip_serializing_if = "Option::is_none")]
122    pub account: Option<String>,
123    /// A `signed` hook whose key only this committer holds: every push on it.
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub key: Option<String>,
126}
127
128/// A credential the HTTP source sends.
129#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
130#[serde(rename_all = "camelCase", deny_unknown_fields)]
131pub struct SourceAuth {
132    /// The header, such as `Authorization` or `PRIVATE-TOKEN`.
133    pub header: String,
134    /// Its whole value, as `env:VAR` or `file:PATH`.
135    pub value: String,
136}
137
138/// Where the pushed commit's files are read: a local git repository or a forge's raw
139/// endpoint ([`source`]).
140#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
141#[serde(rename_all = "camelCase", deny_unknown_fields)]
142pub struct SourceConfig {
143    /// A git repository on this machine, relative to the project.
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub git: Option<PathBuf>,
146    /// The remote the local repository fetches a missing commit from.
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub fetch: Option<String>,
149    /// A raw-file URL template ([`HttpCommitSource`]).
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    pub http: Option<String>,
152    /// The credential the HTTP source sends.
153    #[serde(default, skip_serializing_if = "Option::is_none")]
154    pub auth: Option<SourceAuth>,
155}
156
157/// `repository.json`: files and git as an entry point (spec 3.5 §7.8.2, A-I24).
158///
159/// ```json
160/// {
161///   "branch": "main",
162///   "source": { "git": "../juniper-content", "fetch": "origin" },
163///   "hooks": [
164///     { "name": "github", "forge": "github", "secret": "env:JUNIPER_GITHUB_WEBHOOK_SECRET" },
165///     { "name": "studio", "forge": "signed", "secret": "env:JUNIPER_STUDIO_WHSEC" }
166///   ],
167///   "committers": [
168///     { "id": "wanjiru", "account": "github:wanjiru-k" },
169///     { "id": "newsdesk", "key": "studio" }
170///   ]
171/// }
172/// ```
173///
174/// # Example
175///
176/// ```rust
177/// use adk_website::repository::RepositoryConfig;
178///
179/// let config: RepositoryConfig = serde_json::from_str(r#"{
180///   "source": { "http": "https://raw.githubusercontent.com/{repository}/{commit}/{path}" },
181///   "hooks": [{ "name": "github", "forge": "github", "secret": "env:SECRET" }],
182///   "committers": [{ "id": "wanjiru", "account": "github:wanjiru-k" }]
183/// }"#).unwrap();
184/// assert_eq!(config.branch, "main");
185/// assert!(config.validate().is_ok());
186/// ```
187#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
188#[serde(rename_all = "camelCase", deny_unknown_fields)]
189pub struct RepositoryConfig {
190    /// The branch whose pushes propose releases; `main` by default.
191    #[serde(default = "default_branch")]
192    pub branch: String,
193    /// Where the pushed commit's files are read.
194    pub source: SourceConfig,
195    /// The signed webhooks.
196    pub hooks: Vec<HookConfig>,
197    /// The authorised committers; anyone else's push becomes a signal.
198    pub committers: Vec<CommitterConfig>,
199}
200
201impl RepositoryConfig {
202    /// Checks the hooks, the committers and the source.
203    ///
204    /// # Errors
205    ///
206    /// A hook name that is not a path segment or is listed twice; a committer listed twice,
207    /// with both or neither of `account` and `key`, an account on a hook that is not a
208    /// forge's, a key that is not a `signed` hook or is held by two committers; a source
209    /// with both or neither of `git` and `http`.
210    pub fn validate(&self) -> Result<()> {
211        let mut hooks = BTreeMap::new();
212        for hook in &self.hooks {
213            let valid = !hook.name.is_empty()
214                && hook.name.len() <= 64
215                && hook.name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
216            if !valid {
217                return Err(config(format!(
218                    "{REPOSITORY_FILE}: hook `{}` needs a name of letters, digits, `-` and `_`; \
219                     it is served at /hooks/<name>",
220                    hook.name
221                )));
222            }
223            if hooks.insert(hook.name.as_str(), hook.forge).is_some() {
224                return Err(config(format!(
225                    "{REPOSITORY_FILE}: hook `{}` is listed twice",
226                    hook.name
227                )));
228            }
229        }
230        let mut ids = std::collections::BTreeSet::new();
231        let mut keys = std::collections::BTreeSet::new();
232        for committer in &self.committers {
233            if committer.id.trim().is_empty() || !ids.insert(committer.id.as_str()) {
234                return Err(config(format!(
235                    "{REPOSITORY_FILE}: committer `{}` needs an id listed once",
236                    committer.id
237                )));
238            }
239            match (&committer.account, &committer.key) {
240                (Some(account), None) => {
241                    let forge = account
242                        .split_once(':')
243                        .filter(|(_, user)| !user.is_empty())
244                        .and_then(|(hook, _)| hooks.get(hook));
245                    if !matches!(forge, Some(Forge::Github | Forge::Gitlab)) {
246                        return Err(config(format!(
247                            "{REPOSITORY_FILE}: committer `{}`'s account `{account}` is not \
248                             `<hook>:<username>` on a github or gitlab hook",
249                            committer.id
250                        )));
251                    }
252                }
253                (None, Some(key)) => {
254                    if hooks.get(key.as_str()) != Some(&Forge::Signed) || !keys.insert(key.as_str())
255                    {
256                        return Err(config(format!(
257                            "{REPOSITORY_FILE}: committer `{}`'s key `{key}` must be a signed \
258                             hook no other committer holds",
259                            committer.id
260                        )));
261                    }
262                }
263                _ => {
264                    return Err(config(format!(
265                        "{REPOSITORY_FILE}: committer `{}` needs an `account` or a `key`",
266                        committer.id
267                    )));
268                }
269            }
270        }
271        if self.source.git.is_some() == self.source.http.is_some() {
272            return Err(config(format!(
273                "{REPOSITORY_FILE}: the source is either `git` (a local repository) or `http` (a \
274                 raw-file URL template)"
275            )));
276        }
277        Ok(())
278    }
279
280    /// The committer of `push` on `hook`: the listed account that pushed on a forge's hook,
281    /// the key's holder on a signed one.
282    pub fn committer(&self, hook: &HookConfig, push: &PushEvent) -> Option<&CommitterConfig> {
283        match hook.forge {
284            Forge::Signed => {
285                self.committers.iter().find(|c| c.key.as_deref() == Some(hook.name.as_str()))
286            }
287            Forge::Github | Forge::Gitlab => {
288                let pusher = push.pusher.as_deref()?;
289                let account = format!("{}:{pusher}", hook.name);
290                self.committers.iter().find(|c| c.account.as_deref() == Some(account.as_str()))
291            }
292        }
293    }
294}
295
296/// A push to the content repository (spec 3.5 §7.8.2), as GitHub, GitLab or the plain
297/// signed form describe it.
298///
299/// The plain signed form is GitHub's shape, reduced:
300///
301/// ```json
302/// { "repository": "juniper/site", "ref": "refs/heads/main",
303///   "before": "<commit id>", "after": "<commit id>",
304///   "commits": [{ "id": "<commit id>", "added": [], "modified": ["content/pages/hours/en.md"], "removed": [] }] }
305/// ```
306#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
307#[serde(rename_all = "camelCase")]
308pub struct PushEvent {
309    /// The repository's name, such as `juniper/site`.
310    pub repository: String,
311    /// The branch pushed to; `None` for a tag or another ref.
312    pub branch: Option<String>,
313    /// The commit before the push, when the branch existed.
314    pub before: Option<String>,
315    /// The pushed commit; `None` when the push deletes the branch.
316    pub commit: Option<String>,
317    /// The forge account that pushed.
318    pub pusher: Option<String>,
319    /// The files the push's commits change, each once with its last change.
320    pub files: Vec<FileChange>,
321}
322
323impl PushEvent {
324    /// Reads a push from `payload` as `forge` sends it; `None` when it is not a push.
325    ///
326    /// # Example
327    ///
328    /// ```rust
329    /// use adk_website::repository::{Forge, PushEvent};
330    /// use serde_json::json;
331    ///
332    /// let sha = "a".repeat(40);
333    /// let push = PushEvent::parse(Forge::Github, &json!({
334    ///     "ref": "refs/heads/main", "before": "0".repeat(40), "after": sha,
335    ///     "repository": { "full_name": "juniper/site" },
336    ///     "pusher": { "name": "wanjiru-k" }, "sender": { "login": "wanjiru-k" },
337    ///     "commits": [{ "id": sha, "added": ["content/pages/hours/en.md"], "modified": [], "removed": [] }]
338    /// })).unwrap();
339    /// assert_eq!((push.branch.as_deref(), push.pusher.as_deref()), (Some("main"), Some("wanjiru-k")));
340    /// assert_eq!(push.before, None, "a new branch has no commit before");
341    /// assert!(PushEvent::parse(Forge::Github, &json!({ "zen": "ping" })).is_none());
342    /// ```
343    pub fn parse(forge: Forge, payload: &Value) -> Option<Self> {
344        let text = |pointer: &str| {
345            payload
346                .pointer(pointer)
347                .and_then(Value::as_str)
348                .map(str::trim)
349                .filter(|s| !s.is_empty())
350        };
351        if forge == Forge::Gitlab && text("/object_kind").is_some_and(|kind| kind != "push") {
352            return None;
353        }
354        let reference = text("/ref")?;
355        let after = text("/after")?;
356        payload.get("commits").and_then(Value::as_array)?;
357        let commit_id = |id: Option<&str>| {
358            id.filter(|id| is_commit_id(id) && id.bytes().any(|b| b != b'0')).map(str::to_string)
359        };
360        let deleted = payload.get("deleted").and_then(Value::as_bool) == Some(true);
361        let repository = match forge {
362            Forge::Github => text("/repository/full_name"),
363            Forge::Gitlab => text("/project/path_with_namespace"),
364            Forge::Signed => text("/repository")
365                .or_else(|| text("/repository/full_name"))
366                .or_else(|| text("/repository/name")),
367        }
368        .unwrap_or_default()
369        .to_string();
370        let pusher = match forge {
371            Forge::Github => text("/sender/login").or_else(|| text("/pusher/name")),
372            Forge::Gitlab => text("/user_username"),
373            Forge::Signed => None,
374        }
375        .map(str::to_string);
376        let mut last: BTreeMap<String, (usize, bool)> = BTreeMap::new();
377        let mut order = 0;
378        for commit in payload["commits"].as_array().into_iter().flatten() {
379            for (list, removed) in [("added", false), ("modified", false), ("removed", true)] {
380                for path in commit.get(list).and_then(Value::as_array).into_iter().flatten() {
381                    if let Some(path) = path.as_str() {
382                        order += 1;
383                        last.insert(path.to_string(), (order, removed));
384                    }
385                }
386            }
387        }
388        let mut files: Vec<(usize, FileChange)> = last
389            .into_iter()
390            .map(|(path, (order, removed))| (order, FileChange { path, removed }))
391            .collect();
392        files.sort();
393        Some(Self {
394            repository,
395            branch: reference.strip_prefix("refs/heads/").map(str::to_string),
396            before: commit_id(text("/before")),
397            commit: if deleted { None } else { commit_id(Some(after)) },
398            pusher,
399            files: files.into_iter().map(|(_, file)| file).collect(),
400        })
401    }
402}
403
404/// What became of a push (spec 3.5 §7.8.2, A-I24).
405#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
406#[serde(rename_all = "snake_case")]
407pub enum PushState {
408    /// Not for publishing: no content file changed.
409    Ignored,
410    /// From no authorised committer: one signal, nothing authored.
411    Signalled,
412    /// A file that is not content, or the release refused it (A-I1).
413    Refused,
414    /// The per-change checks held it.
415    Held,
416    /// Waiting for the owner's decision card.
417    Proposed,
418    /// Approved by the owner, waiting for the rest of the approval chain (A-I23).
419    Approving,
420    /// Released and published.
421    Published,
422    /// Saved to publish at its `publish_at`.
423    Scheduled,
424    /// Declined, or the card expired.
425    Declined,
426}
427
428/// One push the entry took, kept in `data/repository/pushes.json`.
429#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
430#[serde(rename_all = "camelCase")]
431pub struct PushRecord {
432    /// The hook it arrived on.
433    pub hook: String,
434    /// The delivery id.
435    pub delivery: String,
436    /// The repository.
437    pub repository: String,
438    /// The branch.
439    pub branch: String,
440    /// The pushed commit.
441    pub commit: String,
442    /// The authorised committer, when one pushed.
443    #[serde(default, skip_serializing_if = "Option::is_none")]
444    pub committer: Option<String>,
445    /// When it arrived.
446    pub at: DateTime<Utc>,
447    /// What became of it.
448    pub state: PushState,
449    /// The owner's decision card.
450    #[serde(default, skip_serializing_if = "Option::is_none")]
451    pub card: Option<String>,
452    /// The items it changes.
453    #[serde(default, skip_serializing_if = "Vec::is_empty")]
454    pub items: Vec<ContentId>,
455    /// Why it was refused or held.
456    #[serde(default, skip_serializing_if = "Option::is_none")]
457    pub detail: Option<String>,
458    /// The release it published in.
459    #[serde(default, skip_serializing_if = "Option::is_none")]
460    pub release: Option<u64>,
461}
462
463/// What [`RepositoryEntry::receive`] did with one delivery.
464#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
465#[serde(rename_all = "camelCase", tag = "outcome")]
466pub enum PushOutcome {
467    /// Not a push to the site's branch, or no content changed.
468    Ignored {
469        /// Why.
470        reason: String,
471    },
472    /// The commit was taken before: a replayed delivery.
473    Duplicate {
474        /// The commit.
475        commit: String,
476    },
477    /// Taken: the record says what became of it.
478    Taken(Box<PushRecord>),
479}
480
481/// What [`RepositoryEntry::open`] builds the entry from beyond `repository.json`.
482pub struct RepositoryParts {
483    /// The site.
484    pub site: SiteRef,
485    /// The person whose decision cards approve releases.
486    pub owner: String,
487    /// The runtime whose pipeline releases.
488    pub runtime: Arc<SiteRuntime>,
489    /// Where decision cards go: the kernel's approval service.
490    pub approvals: Arc<dyn ApprovalService>,
491    /// Where an unauthorised push's signal goes: the back office.
492    pub signals: Arc<dyn SignalEmitter>,
493    /// The source, when not the one `repository.json` names.
494    pub source: Option<Arc<dyn CommitSource>>,
495}
496
497/// A change waiting for its decision, with the preview the card names.
498struct Pending {
499    draft: Draft,
500    preview: Preview,
501}
502
503/// Files and git as an entry point for one site (spec 3.5 §7.8.2, A-I23, A-I24).
504pub struct RepositoryEntry {
505    parts: RepositoryParts,
506    config: RepositoryConfig,
507    source: Arc<dyn CommitSource>,
508    hooks: Vec<WebhookHook>,
509    journal: PathBuf,
510    records: Mutex<Vec<PushRecord>>,
511    pending: Mutex<BTreeMap<String, Pending>>,
512}
513
514impl std::fmt::Debug for RepositoryEntry {
515    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
516        f.debug_struct("RepositoryEntry")
517            .field("site", &self.parts.site)
518            .field("branch", &self.config.branch)
519            .finish_non_exhaustive()
520    }
521}
522
523impl RepositoryEntry {
524    /// The entry of the project at `paths`, from its `repository.json`; `None` without the
525    /// file. Each hook's secret is read now.
526    ///
527    /// # Errors
528    ///
529    /// A file that does not parse or [validate](RepositoryConfig::validate), a secret written
530    /// in the file or not found, or a source that cannot be built.
531    pub fn open(paths: &ProjectPaths, parts: RepositoryParts) -> Result<Option<Self>> {
532        let Some(settings) = read_json::<RepositoryConfig>(&paths.root().join(REPOSITORY_FILE))?
533        else {
534            return Ok(None);
535        };
536        settings.validate()?;
537        let source: Arc<dyn CommitSource> = match (&parts.source, &settings.source) {
538            (Some(source), _) => source.clone(),
539            (None, SourceConfig { git: Some(dir), fetch, .. }) => {
540                let mut source = LocalGitSource::new(paths.root().join(dir));
541                if let Some(remote) = fetch {
542                    source = source.with_fetch(remote.clone());
543                }
544                Arc::new(source)
545            }
546            (None, SourceConfig { http: Some(template), auth, .. }) => {
547                let mut source = HttpCommitSource::new(template.clone())?;
548                if let Some(auth) = auth {
549                    let value = secret_in(paths, REPOSITORY_FILE, &auth.value)?;
550                    source = source.with_auth(&auth.header, value)?;
551                }
552                Arc::new(source)
553            }
554            (None, _) => return Err(config("repository.json names no source")),
555        };
556        let app = parts.site.name.clone();
557        let site = parts.site.id;
558        let mut hooks = Vec::new();
559        for hook in &settings.hooks {
560            let secret = secret_in(paths, REPOSITORY_FILE, &hook.secret)?;
561            let mut served = match hook.forge {
562                Forge::Github => WebhookHook::forge(
563                    &hook.name,
564                    ForgeSignature::GitHub(ForgeSecret::new(secret.expose()).map_err(config)?),
565                    &app,
566                    REPOSITORY_WORKFLOW,
567                ),
568                Forge::Gitlab => WebhookHook::forge(
569                    &hook.name,
570                    ForgeSignature::GitLab(ForgeSecret::new(secret.expose()).map_err(config)?),
571                    &app,
572                    REPOSITORY_WORKFLOW,
573                ),
574                Forge::Signed => {
575                    let key = adk_core::webhook::WebhookSecret::from_base64(secret.expose())
576                        .map_err(|e| {
577                            config(format!("{REPOSITORY_FILE}: hook `{}`: {e}", hook.name))
578                        })?;
579                    WebhookHook::new(
580                        &hook.name,
581                        adk_core::webhook::WebhookVerifier::new(key),
582                        &app,
583                        REPOSITORY_WORKFLOW,
584                    )
585                }
586            };
587            let app = app.clone();
588            served = served.with_queue(QueueClass::BACKGROUND).with_max_pending(100).with_mapper(
589                move |delivery| {
590                    Ok(NewRun::new(
591                        QueueClass::BACKGROUND,
592                        app.clone(),
593                        format!("repository:{}", delivery.hook),
594                        REPOSITORY_WORKFLOW,
595                        json!({
596                            "site": site,
597                            "hook": delivery.hook,
598                            "delivery": delivery.webhook.id,
599                            "payload": delivery.payload,
600                        }),
601                    ))
602                },
603            );
604            hooks.push(served);
605        }
606        let journal = paths.data().join("repository").join("pushes.json");
607        let records: Vec<PushRecord> = read_json(&journal)?.unwrap_or_default();
608        Ok(Some(Self {
609            parts,
610            config: settings,
611            source,
612            hooks,
613            journal,
614            records: Mutex::new(records),
615            pending: Mutex::new(BTreeMap::new()),
616        }))
617    }
618
619    /// The configuration.
620    pub fn config(&self) -> &RepositoryConfig {
621        &self.config
622    }
623
624    /// The pushes taken so far, oldest first.
625    pub async fn records(&self) -> Vec<PushRecord> {
626        self.records.lock().await.clone()
627    }
628
629    /// The hooks at `/hooks/{name}`: `adk-server`'s webhook ingress over `runs`, the store
630    /// the site's kernel claims runs from, so each push is one durable run keyed by its
631    /// delivery id.
632    pub fn router(&self, runs: Arc<dyn DurableRunStore>) -> axum::Router {
633        let ingress =
634            self.hooks.iter().cloned().fold(WebhookIngress::new(runs), WebhookIngress::with_hook);
635        webhook_ingress_router(ingress)
636    }
637
638    /// Runs one push's workflow input: `{site, hook, delivery, payload}`.
639    ///
640    /// # Errors
641    ///
642    /// As [`receive`](Self::receive), or an input without those members.
643    pub async fn execute(&self, input: &adk_server::background::WorkflowState) -> Result<Value> {
644        let text = |key: &str| {
645            input
646                .get(key)
647                .and_then(Value::as_str)
648                .ok_or_else(|| config(format!("a {REPOSITORY_WORKFLOW} run names its `{key}`")))
649        };
650        let outcome = self
651            .receive(text("hook")?, text("delivery")?, input.get("payload").unwrap_or(&Value::Null))
652            .await?;
653        serde_json::to_value(outcome).map_err(config)
654    }
655
656    /// Takes one verified delivery (spec 3.5 §7.8.2, A-I24): ignores what is not a push to
657    /// the site's branch, answers a commit taken before as a duplicate, files a signal for a
658    /// push from no authorised committer, and otherwise reads the changed content files at
659    /// the commit, drafts and previews the change, and submits the owner's decision card.
660    ///
661    /// # Errors
662    ///
663    /// A source that cannot be read, the approval service's error, or the journal's; the
664    /// kernel retries the run.
665    pub async fn receive(
666        &self,
667        hook: &str,
668        delivery: &str,
669        payload: &Value,
670    ) -> Result<PushOutcome> {
671        let ignored = |reason: String| Ok(PushOutcome::Ignored { reason });
672        let Some(hook) = self.config.hooks.iter().find(|h| h.name == hook) else {
673            return ignored(format!("no hook `{hook}`"));
674        };
675        let Some(push) = PushEvent::parse(hook.forge, payload) else {
676            return ignored("not a push".to_string());
677        };
678        if push.branch.as_deref() != Some(self.config.branch.as_str()) {
679            return ignored(format!("not a push to {}", self.config.branch));
680        }
681        let Some(commit) = push.commit.clone() else {
682            return ignored("the push deletes the branch".to_string());
683        };
684        // One push at a time, so a replay racing its original proposes nothing twice. A commit
685        // an authorised committer pushed is taken once on any hook; one only signalled is
686        // taken once on its own hook, and a listed committer may still push it.
687        let mut records = self.records.lock().await;
688        if records.iter().any(|r| {
689            r.repository == push.repository
690                && r.commit == commit
691                && (r.committer.is_some() || r.hook == hook.name)
692        }) {
693            tracing::info!(website.repository.commit = %commit, "a replayed push is taken once");
694            return Ok(PushOutcome::Duplicate { commit });
695        }
696        let mut record = PushRecord {
697            hook: hook.name.clone(),
698            delivery: delivery.to_string(),
699            repository: push.repository.clone(),
700            branch: self.config.branch.clone(),
701            commit: commit.clone(),
702            committer: None,
703            at: Utc::now(),
704            state: PushState::Ignored,
705            card: None,
706            items: Vec::new(),
707            detail: None,
708            release: None,
709        };
710        match self.config.committer(hook, &push) {
711            None => {
712                self.signal(&hook.name, &commit).await?;
713                record.state = PushState::Signalled;
714            }
715            Some(committer) => {
716                record.committer = Some(committer.id.clone());
717                self.propose(&push, &commit, committer, &mut record).await?;
718            }
719        }
720        records.push(record.clone());
721        self.keep(&mut records).await?;
722        Ok(PushOutcome::Taken(Box::new(record)))
723    }
724
725    /// The signal a push from no authorised committer files (spec 3.5 §7.10, A-I3, A-I24):
726    /// typed fields only, no account name and no file.
727    async fn signal(&self, hook: &str, commit: &str) -> Result<()> {
728        tracing::info!(website.repository.hook = hook, website.repository.commit = %commit, "a push from no authorised committer becomes a signal");
729        self.parts
730            .signals
731            .emit(Signal {
732                id: uuid::Uuid::new_v4(),
733                kind: SignalKind::InboundMessage {
734                    channel: Channel::from("repository"),
735                    thread_ref: ThreadRef(format!("{hook}:{}", &commit[..12])),
736                    category: MessageCategory::Other,
737                },
738                emitted_by: format!("repository:{hook}"),
739                emitted_at: Utc::now(),
740            })
741            .await
742    }
743
744    /// The content files a push changes: the source's own list when it has one.
745    async fn changed(&self, push: &PushEvent, commit: &str) -> Result<Vec<FileChange>> {
746        let listed = self
747            .source
748            .changes(&push.repository, push.before.as_deref(), commit)
749            .await?
750            .unwrap_or_else(|| push.files.clone());
751        let prefix = format!("{CONTENT_DIR}/");
752        Ok(listed
753            .into_iter()
754            .filter(|file| file.path.starts_with(&prefix) && file.path.ends_with(".md"))
755            .collect())
756    }
757
758    /// The change a push makes: each changed content file read at the commit, each removed
759    /// one withdrawn; `Err` with the reason for a file that is not a content item.
760    async fn change(
761        &self,
762        push: &PushEvent,
763        commit: &str,
764        committer: &CommitterConfig,
765    ) -> Result<std::result::Result<Change, String>> {
766        let mut items: Vec<ContentItem> = Vec::new();
767        for file in self.changed(push, commit).await? {
768            let bytes = match file.removed {
769                true => None,
770                false => self.source.read(&push.repository, commit, &file.path).await?,
771            };
772            match bytes {
773                Some(bytes) => {
774                    let Ok(text) = String::from_utf8(bytes.to_vec()) else {
775                        return Ok(Err(format!("{} is not UTF-8 text", file.path)));
776                    };
777                    match parse_content_file(&file.path, &text) {
778                        Ok(item) => items.push(item),
779                        Err(error) => return Ok(Err(error.to_string())),
780                    }
781                }
782                None => {
783                    let id = ContentId(
784                        file.path
785                            .trim_start_matches(&format!("{CONTENT_DIR}/"))
786                            .trim_end_matches(".md")
787                            .to_string(),
788                    );
789                    let store = self.parts.runtime.store();
790                    if let Some(mut item) = store.get(&id).await.map_err(config)? {
791                        item.fields.insert("withdrawal".into(), json!({ "mode": "gone" }));
792                        item.state = ContentState::Withdrawn;
793                        items.push(item);
794                    }
795                }
796            }
797        }
798        Ok(Ok(Change {
799            items,
800            media: Vec::new(),
801            entry: EntryPoint::Repository { committer: committer.id.clone() },
802            proposer: committer.id.clone(),
803            job: REPOSITORY_JOB.to_string(),
804            action_class: "publish".to_string(),
805        }))
806    }
807
808    /// Drafts, checks and previews an authorised committer's push, and cards it.
809    async fn propose(
810        &self,
811        push: &PushEvent,
812        commit: &str,
813        committer: &CommitterConfig,
814        record: &mut PushRecord,
815    ) -> Result<()> {
816        let change = match self.change(push, commit, committer).await? {
817            Ok(change) if change.items.is_empty() => {
818                record.detail = Some("no content file changed".to_string());
819                return Ok(());
820            }
821            Ok(change) => change,
822            Err(reason) => {
823                record.state = PushState::Refused;
824                record.detail = Some(reason);
825                return Ok(());
826            }
827        };
828        record.items = change.items.iter().map(|item| item.id.clone()).collect();
829        let pipeline = self.parts.runtime.pipeline();
830        let draft = match pipeline.draft(change).await {
831            Ok(draft) => draft,
832            Err(error) => {
833                record.state = PushState::Refused;
834                record.detail = Some(error.to_string());
835                return Ok(());
836            }
837        };
838        let preview = match pipeline.preview(&draft).await {
839            Ok(preview) => preview,
840            Err(error) => {
841                record.state = PushState::Refused;
842                record.detail = Some(error.to_string());
843                return Ok(());
844            }
845        };
846        if preview.gate.refuses_release() || !preview.gate.passed() {
847            record.state =
848                if preview.gate.refuses_release() { PushState::Refused } else { PushState::Held };
849            record.detail = Some(preview.gate.summary());
850            return Ok(());
851        }
852        let card = self.card(push, commit, committer, &draft, &preview).await?;
853        tracing::info!(website.repository.commit = %commit, website.repository.card = %card, "a push waits for the owner's decision");
854        record.state = PushState::Proposed;
855        record.card = Some(card.clone());
856        self.pending.lock().await.insert(card, Pending { draft, preview });
857        Ok(())
858    }
859
860    /// Submits the owner's decision card for a previewed push, or finds the one submitted
861    /// before a restart.
862    async fn card(
863        &self,
864        push: &PushEvent,
865        commit: &str,
866        committer: &CommitterConfig,
867        draft: &Draft,
868        preview: &Preview,
869    ) -> Result<String> {
870        let id = format!("site-repository-{}-{}", self.parts.site.id, &commit[..12]);
871        if self.parts.approvals.get(&id).await?.is_some() {
872            return Ok(id);
873        }
874        let pages = preview.diff.len();
875        let summary = format!(
876            "{} pushed {} to {}: {} item{} and {pages} page{} change. Publish it or decline it.",
877            committer.id,
878            &commit[..7],
879            self.config.branch,
880            draft.ids.len(),
881            if draft.ids.len() == 1 { "" } else { "s" },
882            if pages == 1 { "" } else { "s" },
883        );
884        let args = json!({
885            "repository": push.repository,
886            "branch": self.config.branch,
887            "commit": commit,
888            "committer": committer.id,
889            "items": draft.ids,
890            "preview": preview.staged.digest,
891            "diff": preview.diff,
892        });
893        let call = ToolConfirmationRequest::new(REPOSITORY_RELEASE, args);
894        let owner = self.parts.owner.clone();
895        let scope =
896            ApprovalScope::new(self.parts.site.name.clone(), owner.clone(), "site-repository");
897        let policy = ApprovalPolicy::new([ApproverSelector::human(owner)]);
898        let request = ApprovalRequest::new(id.clone(), scope, &call, policy)
899            .with_summary(summary)
900            .with_risk(ApprovalRisk::Medium);
901        self.parts.approvals.submit(request).await?;
902        Ok(id)
903    }
904
905    /// Applies the owner's decided cards (spec 3.5 §7.8.2 step 4, A-I23): an approval records
906    /// the owner's vote and releases once the approval chain is satisfied; a refusal or an
907    /// expiry declines the push. Returns the records it changed.
908    ///
909    /// # Errors
910    ///
911    /// The approval service's, the source's or the journal's error.
912    pub async fn step(&self) -> Result<Vec<PushRecord>> {
913        let mut records = self.records.lock().await;
914        let mut changed = Vec::new();
915        for record in records.iter_mut() {
916            if !matches!(record.state, PushState::Proposed | PushState::Approving) {
917                continue;
918            }
919            let Some(card) = record.card.clone() else { continue };
920            let Some(request) = self.parts.approvals.get(&card).await? else { continue };
921            match request.state {
922                ApprovalState::Pending | ApprovalState::Responded => continue,
923                ApprovalState::Rejected | ApprovalState::Expired | ApprovalState::Cancelled => {
924                    self.pending.lock().await.remove(&card);
925                    record.state = PushState::Declined;
926                    record.detail = request.decisions.last().and_then(|d| d.reason.clone());
927                    changed.push(record.clone());
928                }
929                ApprovalState::Approved => {
930                    let by = request
931                        .decisions
932                        .last()
933                        .map_or_else(|| self.parts.owner.clone(), |d| d.approver.id.clone());
934                    if self.release(record, &card, &by).await? {
935                        changed.push(record.clone());
936                    }
937                }
938            }
939        }
940        if !changed.is_empty() {
941            self.keep(&mut records).await?;
942        }
943        Ok(changed)
944    }
945
946    /// Releases an approved push; `false` while its approval chain still waits.
947    async fn release(&self, record: &mut PushRecord, card: &str, by: &str) -> Result<bool> {
948        let mut pending = self.pending.lock().await;
949        if !pending.contains_key(card) {
950            // A restart forgot the draft: the commit is read and previewed again.
951            let Some(rebuilt) = self.rebuild(record).await? else {
952                record.state = PushState::Refused;
953                record.detail = Some("the commit no longer previews".to_string());
954                return Ok(true);
955            };
956            pending.insert(card.to_string(), rebuilt);
957        }
958        let Some(Pending { draft, preview }) = pending.get(card) else { return Ok(false) };
959        let pipeline = self.parts.runtime.pipeline();
960        let mut decided = pipeline.approve(draft, preview).await.map_err(config)?;
961        if let (ApprovalDecision::Pending { ticket }, PushState::Proposed) =
962            (&decided, &record.state)
963        {
964            // The owner's card is the owner's vote on the release's request under an approval
965            // chain (A-I23); a vote that cannot count is left out.
966            let approvals = self.parts.runtime.approvals();
967            if let Some(request) = approvals.get(ticket).await? {
968                match approvals.approve(ticket, request.version, &SubjectRef::human(by)).await {
969                    Ok(_) => decided = pipeline.approve(draft, preview).await.map_err(config)?,
970                    Err(error) => {
971                        tracing::info!(website.release.request = %ticket, error = %error, "the owner's vote does not count for the chain");
972                    }
973                }
974            }
975        }
976        let decision = match decided {
977            ApprovalDecision::Pending { .. } => {
978                let waiting = record.state != PushState::Approving;
979                record.state = PushState::Approving;
980                return Ok(waiting);
981            }
982            ApprovalDecision::Rejected { by, reason } => {
983                pending.remove(card);
984                record.state = PushState::Declined;
985                record.detail = Some(format!("{by}: {reason}"));
986                return Ok(true);
987            }
988            ApprovalDecision::Approved { decision, .. } => {
989                decision.unwrap_or_else(|| format!("approval:{card}"))
990            }
991        };
992        let Some(Pending { draft, preview }) = pending.remove(card) else { return Ok(false) };
993        let outcome = pipeline.complete(&draft, Some(decision)).await;
994        let _ = tokio::fs::remove_dir_all(&preview.staged.root).await;
995        match outcome.map_err(config)? {
996            PipelineOutcome::Published(published) => {
997                record.state = PushState::Published;
998                record.release = Some(published.staged.manifest.seq);
999            }
1000            PipelineOutcome::Scheduled { .. } => record.state = PushState::Scheduled,
1001            PipelineOutcome::Held(report) => {
1002                record.state = PushState::Held;
1003                record.detail = Some(report.summary());
1004            }
1005            PipelineOutcome::Rejected { by, reason } => {
1006                record.state = PushState::Declined;
1007                record.detail = Some(format!("{by}: {reason}"));
1008            }
1009            PipelineOutcome::Pending { .. } => record.state = PushState::Approving,
1010        }
1011        tracing::info!(website.repository.commit = %record.commit, website.repository.state = ?record.state, "the owner's decision on a push is applied");
1012        Ok(true)
1013    }
1014
1015    /// The draft and preview of a recorded push, read again from its commit.
1016    async fn rebuild(&self, record: &PushRecord) -> Result<Option<Pending>> {
1017        let Some(committer) =
1018            self.config.committers.iter().find(|c| Some(&c.id) == record.committer.as_ref())
1019        else {
1020            return Ok(None);
1021        };
1022        let push = PushEvent {
1023            repository: record.repository.clone(),
1024            branch: Some(record.branch.clone()),
1025            before: None,
1026            commit: Some(record.commit.clone()),
1027            pusher: None,
1028            files: record
1029                .items
1030                .iter()
1031                .map(|id| FileChange { path: format!("{CONTENT_DIR}/{}.md", id.0), removed: false })
1032                .collect(),
1033        };
1034        let Ok(change) = self.change(&push, &record.commit, committer).await? else {
1035            return Ok(None);
1036        };
1037        let pipeline = self.parts.runtime.pipeline();
1038        let draft = pipeline.draft(change).await.map_err(config)?;
1039        let preview = pipeline.preview(&draft).await.map_err(config)?;
1040        Ok(preview.gate.passed().then_some(Pending { draft, preview }))
1041    }
1042
1043    /// Writes the journal, keeping the newest records.
1044    async fn keep(&self, records: &mut Vec<PushRecord>) -> Result<()> {
1045        if records.len() > KEPT_RECORDS {
1046            let excess = records.len() - KEPT_RECORDS;
1047            records.drain(..excess);
1048        }
1049        write_journal(&self.journal, records).await
1050    }
1051
1052    /// Applies the owner's decisions every `idle` until aborted.
1053    pub fn spawn(self: Arc<Self>, idle: Duration) -> JoinHandle<()> {
1054        tokio::spawn(async move {
1055            loop {
1056                if let Err(error) = self.step().await {
1057                    tracing::warn!(error = %error, "the repository entry's step failed");
1058                }
1059                tokio::time::sleep(idle).await;
1060            }
1061        })
1062    }
1063}
1064
1065async fn write_journal(path: &Path, records: &[PushRecord]) -> Result<()> {
1066    if let Some(parent) = path.parent() {
1067        tokio::fs::create_dir_all(parent).await.map_err(config)?;
1068    }
1069    let bytes = serde_json::to_vec_pretty(records).map_err(config)?;
1070    let temporary = path.with_extension("json.tmp");
1071    tokio::fs::write(&temporary, bytes).await.map_err(config)?;
1072    tokio::fs::rename(&temporary, path).await.map_err(config)
1073}
1074
1075#[cfg(test)]
1076mod tests {
1077    use super::*;
1078
1079    fn sha(c: char) -> String {
1080        c.to_string().repeat(40)
1081    }
1082
1083    #[test]
1084    fn each_forge_names_its_pusher_and_the_last_change_of_each_file() {
1085        let gitlab = PushEvent::parse(
1086            Forge::Gitlab,
1087            &json!({
1088                "object_kind": "push", "ref": "refs/heads/main", "before": sha('1'), "after": sha('2'),
1089                "user_username": "wanjiru", "project": { "path_with_namespace": "news/site" },
1090                "commits": [
1091                    { "id": sha('3'), "added": ["content/a/x/en.md"], "modified": [], "removed": [] },
1092                    { "id": sha('2'), "added": [], "modified": [], "removed": ["content/a/x/en.md"] }
1093                ]
1094            }),
1095        )
1096        .unwrap();
1097        assert_eq!(gitlab.pusher.as_deref(), Some("wanjiru"));
1098        assert_eq!(gitlab.repository, "news/site");
1099        assert_eq!(gitlab.files, [FileChange { path: "content/a/x/en.md".into(), removed: true }]);
1100        let tag = PushEvent::parse(
1101            Forge::Gitlab,
1102            &json!({ "object_kind": "tag_push", "ref": "refs/tags/v1", "after": sha('2'), "commits": [] }),
1103        );
1104        assert!(tag.is_none());
1105        let signed = PushEvent::parse(
1106            Forge::Signed,
1107            &json!({ "repository": "studio/site", "ref": "refs/heads/main", "after": "0".repeat(40), "commits": [] }),
1108        )
1109        .unwrap();
1110        assert_eq!((signed.repository.as_str(), signed.commit), ("studio/site", None));
1111        assert_eq!(signed.pusher, None, "the signed form names no account: its key does");
1112    }
1113
1114    #[test]
1115    fn committers_are_an_account_on_a_forge_hook_or_a_signed_hook_key() {
1116        let hook =
1117            |name: &str, forge| HookConfig { name: name.into(), forge, secret: "env:X".into() };
1118        let mut config = RepositoryConfig {
1119            branch: "main".into(),
1120            source: SourceConfig { git: Some(".".into()), ..SourceConfig::default() },
1121            hooks: vec![hook("github", Forge::Github), hook("studio", Forge::Signed)],
1122            committers: vec![
1123                CommitterConfig {
1124                    id: "wanjiru".into(),
1125                    account: Some("github:wanjiru-k".into()),
1126                    key: None,
1127                },
1128                CommitterConfig {
1129                    id: "newsdesk".into(),
1130                    account: None,
1131                    key: Some("studio".into()),
1132                },
1133            ],
1134        };
1135        config.validate().unwrap();
1136        let push = |pusher: Option<&str>| PushEvent {
1137            repository: "r".into(),
1138            branch: Some("main".into()),
1139            before: None,
1140            commit: Some(sha('a')),
1141            pusher: pusher.map(str::to_string),
1142            files: Vec::new(),
1143        };
1144        let github = &config.hooks[0];
1145        assert_eq!(config.committer(github, &push(Some("wanjiru-k"))).unwrap().id, "wanjiru");
1146        assert!(config.committer(github, &push(Some("mallory"))).is_none());
1147        assert!(config.committer(github, &push(None)).is_none());
1148        assert_eq!(
1149            config.committer(&config.hooks[1], &push(Some("mallory"))).unwrap().id,
1150            "newsdesk"
1151        );
1152
1153        config.committers[1].key = Some("github".into());
1154        assert!(config.validate().is_err(), "a key is a signed hook");
1155        config.committers[1].key = None;
1156        assert!(config.validate().is_err(), "an account or a key");
1157        config.committers[1].account = Some("studio:newsdesk".into());
1158        assert!(config.validate().is_err(), "an account is on a forge's hook");
1159        config.committers.truncate(1);
1160        config.hooks.push(hook("github", Forge::Gitlab));
1161        assert!(config.validate().is_err(), "a hook is listed once");
1162        config.hooks.pop();
1163        config.source.http = Some("https://x/{commit}/{path}".into());
1164        assert!(config.validate().is_err(), "one source");
1165    }
1166}