Skip to main content

adk_kernel/charter/
autonomy.rs

1//! Earned autonomy per job (spec 3.5 §7.11, A-I13).
2
3use std::sync::Arc;
4
5use adk_core::audit_log::{AuditActor, AuditTrail};
6use adk_core::principal::{SubjectKind, SubjectRef};
7use adk_core::{Clock, SystemClock};
8use async_trait::async_trait;
9use awp_types::{AutonomyLevel, Charter, Role};
10use chrono::{DateTime, Duration, Utc};
11use serde::{Deserialize, Serialize};
12use serde_json::json;
13use uuid::Uuid;
14
15use super::store::{CharterStore, is_agent_principal};
16use super::{CharterEvent, CharterEventSink, WEBSITE_AUDIT_KIND, audit, emit, record};
17use crate::error::{KernelError, Result};
18
19/// The autonomy ladder, lowest first (spec 3.5 §7.11).
20///
21/// "Act, reversible only" is Auto over a subset of actions — rollback, read-only, drafts —
22/// so it sits between "act with approval", where every non-read call is held, and "act
23/// within budget", Auto for the job's tool classes.
24const LADDER: [AutonomyLevel; 5] = [
25    AutonomyLevel::Observe,
26    AutonomyLevel::Propose,
27    AutonomyLevel::ActWithApproval,
28    AutonomyLevel::ActReversibleOnly,
29    AutonomyLevel::ActWithinBudget,
30];
31
32/// The rung of `level` on the autonomy ladder, 0 for Observe up to 4 for "act within budget"
33/// (spec 3.5 §7.11); a promotion moves up, a demotion one rung down.
34///
35/// # Example
36///
37/// ```rust
38/// use adk_kernel::charter::ladder_rank;
39/// use awp_types::AutonomyLevel;
40///
41/// assert!(ladder_rank(AutonomyLevel::Propose) < ladder_rank(AutonomyLevel::ActWithApproval));
42/// assert!(ladder_rank(AutonomyLevel::ActReversibleOnly) < ladder_rank(AutonomyLevel::ActWithinBudget));
43/// ```
44pub fn ladder_rank(level: AutonomyLevel) -> usize {
45    LADDER.iter().position(|rung| *rung == level).unwrap_or(0)
46}
47
48/// The rung below `level`, `None` at Observe.
49fn below(level: AutonomyLevel) -> Option<AutonomyLevel> {
50    ladder_rank(level).checked_sub(1).map(|rank| LADDER[rank])
51}
52
53/// The rung above `level`, `None` at the top.
54fn above(level: AutonomyLevel) -> Option<AutonomyLevel> {
55    LADDER.get(ladder_rank(level) + 1).copied()
56}
57
58/// An owner's decision, the proof a promotion takes (spec 3.5 §7.11, A-I13): its id, the
59/// owner who made it, when, and the signed note that seals it.
60///
61/// # Example
62///
63/// ```rust
64/// use adk_core::principal::SubjectRef;
65/// use adk_kernel::charter::OwnerDecision;
66///
67/// let decision = OwnerDecision::new("decision-7", SubjectRef::human("amina"), chrono::Utc::now())
68///     .with_signed_note("note:sha256:cd34");
69/// assert!(decision.check_person().is_ok());
70/// let agent = OwnerDecision::new("decision-8", SubjectRef::human("urn:adk:agent:example/steward"), chrono::Utc::now());
71/// assert!(agent.check_person().is_err());
72/// ```
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
74#[serde(rename_all = "camelCase")]
75#[non_exhaustive]
76pub struct OwnerDecision {
77    /// The decision's id.
78    pub decision_id: String,
79    /// The owner who made it.
80    pub owner: SubjectRef,
81    /// When.
82    pub at: DateTime<Utc>,
83    /// The signed note sealing it, by reference.
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub signed_note: Option<String>,
86}
87
88impl OwnerDecision {
89    /// A decision `decision_id` by `owner` at `at`.
90    pub fn new(decision_id: impl Into<String>, owner: SubjectRef, at: DateTime<Utc>) -> Self {
91        Self { decision_id: decision_id.into(), owner, at, signed_note: None }
92    }
93
94    /// Sets the signed note's reference.
95    #[must_use]
96    pub fn with_signed_note(mut self, note: impl Into<String>) -> Self {
97        self.signed_note = Some(note.into());
98        self
99    }
100
101    /// Refuses a decision no person made: a blank id, a subject not of kind `Human`, or an
102    /// agent identity (A-I13).
103    ///
104    /// # Errors
105    ///
106    /// Returns [`KernelError::Unauthorized`] naming the fault.
107    pub fn check_person(&self) -> Result<()> {
108        if self.decision_id.trim().is_empty() {
109            return Err(KernelError::Unauthorized {
110                reason: "an owner decision needs its decision id".into(),
111            });
112        }
113        if self.owner.kind != SubjectKind::Human || is_agent_principal(&self.owner.id) {
114            return Err(KernelError::Unauthorized {
115                reason: format!(
116                    "{} is not a person: only an owner's decision raises a job's autonomy, and \
117                     the site can only lower it (A-I13)",
118                    self.owner.id
119                ),
120            });
121        }
122        Ok(())
123    }
124}
125
126/// How the owner decided one proposal of a job (spec 3.5 §7.11): what promotion and the
127/// two-rejections rule count.
128///
129/// # Example
130///
131/// ```rust
132/// use adk_kernel::charter::DecisionOutcome;
133///
134/// assert_eq!(serde_json::to_value(DecisionOutcome::ApprovedUnchanged).unwrap(), "approvedUnchanged");
135/// ```
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
137#[serde(rename_all = "camelCase")]
138#[non_exhaustive]
139pub enum DecisionOutcome {
140    /// Approved as proposed.
141    ApprovedUnchanged,
142    /// Approved after the owner edited it.
143    ApprovedWithEdits,
144    /// Rejected.
145    Rejected,
146}
147
148/// One owner decision on one of a job's proposals (spec 3.5 §7.11).
149///
150/// # Example
151///
152/// ```rust
153/// use adk_core::principal::SubjectRef;
154/// use adk_kernel::charter::{DecisionOutcome, JobDecision};
155///
156/// let decision = JobDecision::new(uuid::Uuid::nil(), "review-replies", "approval-1", DecisionOutcome::Rejected, SubjectRef::human("amina"), chrono::Utc::now());
157/// assert_eq!(decision.job, "review-replies");
158/// ```
159#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
160#[serde(rename_all = "camelCase")]
161#[non_exhaustive]
162pub struct JobDecision {
163    /// The site.
164    pub site: Uuid,
165    /// The job.
166    pub job: String,
167    /// The decision's id, such as the approval request's; recorded once.
168    pub id: String,
169    /// How the owner decided.
170    pub outcome: DecisionOutcome,
171    /// Who decided.
172    pub by: SubjectRef,
173    /// When.
174    pub at: DateTime<Utc>,
175}
176
177impl JobDecision {
178    /// A decision `id` on a proposal of `job`.
179    pub fn new(
180        site: Uuid,
181        job: impl Into<String>,
182        id: impl Into<String>,
183        outcome: DecisionOutcome,
184        by: SubjectRef,
185        at: DateTime<Utc>,
186    ) -> Self {
187        Self { site, job: job.into(), id: id.into(), outcome, by, at }
188    }
189}
190
191/// Why a job's autonomy changed (spec 3.5 §7.11): the weekly review says it in these words.
192///
193/// # Example
194///
195/// ```rust
196/// use adk_kernel::charter::AutonomyReason;
197///
198/// let reason = AutonomyReason::GuardrailBreach { guardrail: "unsubscribes".into() };
199/// assert_eq!(reason.describe(), "the unsubscribes guardrail was breached");
200/// ```
201#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
202#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")]
203#[non_exhaustive]
204pub enum AutonomyReason {
205    /// The job's level from the charter's authority when it was first registered.
206    Initial {
207        /// The charter version that set it.
208        #[serde(default, skip_serializing_if = "Option::is_none")]
209        charter_version: Option<u32>,
210    },
211    /// An owner raised it (A-I13).
212    Promoted {
213        /// The owner's decision.
214        decision: OwnerDecision,
215    },
216    /// A guardrail breach lowered it one level.
217    GuardrailBreach {
218        /// The guardrail.
219        guardrail: String,
220    },
221    /// Two owner rejections in a row lowered it one level.
222    OwnerRejections {
223        /// The two decisions.
224        decisions: Vec<String>,
225    },
226    /// An incident in the job's area lowered it one level.
227    Incident {
228        /// The area.
229        area: String,
230        /// The incident.
231        incident: String,
232    },
233    /// The site, or a charter that sets a lower level, lowered it.
234    Lowered {
235        /// Why.
236        reason: String,
237    },
238}
239
240impl AutonomyReason {
241    /// The reason in words.
242    pub fn describe(&self) -> String {
243        match self {
244            Self::Initial { charter_version: Some(version) } => {
245                format!("set by charter version {version}")
246            }
247            Self::Initial { charter_version: None } => "registered".to_string(),
248            Self::Promoted { decision } => {
249                format!("promoted by {}'s decision {}", decision.owner.id, decision.decision_id)
250            }
251            Self::GuardrailBreach { guardrail } => {
252                format!("the {guardrail} guardrail was breached")
253            }
254            Self::OwnerRejections { decisions } => {
255                format!("the owner rejected two proposals in a row ({})", decisions.join(", "))
256            }
257            Self::Incident { area, incident } => format!("incident {incident} in {area}"),
258            Self::Lowered { reason } => reason.clone(),
259        }
260    }
261}
262
263/// A job's autonomy now (spec 3.5 §7.11).
264///
265/// # Example
266///
267/// ```rust
268/// use adk_kernel::charter::JobAutonomy;
269/// use awp_types::AutonomyLevel;
270///
271/// let job = JobAutonomy::new(uuid::Uuid::nil(), "seo", AutonomyLevel::Propose, chrono::Utc::now()).with_area("be-found");
272/// assert_eq!(job.revision, 1);
273/// ```
274#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
275#[serde(rename_all = "camelCase")]
276#[non_exhaustive]
277pub struct JobAutonomy {
278    /// The site.
279    pub site: Uuid,
280    /// The job.
281    pub job: String,
282    /// Its level.
283    pub level: AutonomyLevel,
284    /// The area of its work (§7.20: `run-and-protect`, `be-found`, `serve`, `grow`, `money`,
285    /// `account`), which an incident's demotion matches.
286    #[serde(default, skip_serializing_if = "Option::is_none")]
287    pub area: Option<String>,
288    /// When it entered `level`.
289    pub since: DateTime<Utc>,
290    /// The number of changes so far, 1 after registration.
291    pub revision: u64,
292}
293
294impl JobAutonomy {
295    /// A newly registered job at `level`, revision 1.
296    pub fn new(
297        site: Uuid,
298        job: impl Into<String>,
299        level: AutonomyLevel,
300        at: DateTime<Utc>,
301    ) -> Self {
302        Self { site, job: job.into(), level, area: None, since: at, revision: 1 }
303    }
304
305    /// Sets the job's area.
306    #[must_use]
307    pub fn with_area(mut self, area: impl Into<String>) -> Self {
308        self.area = Some(area.into());
309        self
310    }
311}
312
313/// One change of a job's autonomy, kept as its history (spec 3.5 §7.11).
314#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
315#[serde(rename_all = "camelCase")]
316#[non_exhaustive]
317pub struct AutonomyChange {
318    /// The site.
319    pub site: Uuid,
320    /// The job.
321    pub job: String,
322    /// The job's revision this change makes.
323    pub revision: u64,
324    /// The level it left; `None` at registration.
325    #[serde(default, skip_serializing_if = "Option::is_none")]
326    pub from: Option<AutonomyLevel>,
327    /// The level it entered.
328    pub to: AutonomyLevel,
329    /// Why.
330    pub reason: AutonomyReason,
331    /// Who changed it: the owner for a promotion, the site for a demotion.
332    pub by: SubjectRef,
333    /// When.
334    pub at: DateTime<Utc>,
335}
336
337/// Whether a job has earned a promotion (spec 3.5 §7.11): `streak` unchanged approvals in a
338/// row within the policy's window since its last change, of `needed`.
339#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
340#[serde(rename_all = "camelCase")]
341#[non_exhaustive]
342pub struct PromotionEligibility {
343    /// The site.
344    pub site: Uuid,
345    /// The job.
346    pub job: String,
347    /// Its level.
348    pub level: AutonomyLevel,
349    /// The level a promotion would give it; `None` at the top.
350    #[serde(default, skip_serializing_if = "Option::is_none")]
351    pub next: Option<AutonomyLevel>,
352    /// The unchanged approvals in a row within the window.
353    pub streak: usize,
354    /// How many it needs.
355    pub needed: usize,
356    /// Whether the weekly review offers the promotion.
357    pub eligible: bool,
358}
359
360/// When a job is offered a promotion (spec 3.5 §7.11): `approvals` unchanged approvals in a
361/// row (20) within `within` (30 days), with no breach since its last change.
362///
363/// # Example
364///
365/// ```rust
366/// use adk_kernel::charter::PromotionPolicy;
367///
368/// let policy = PromotionPolicy::default();
369/// assert_eq!((policy.approvals, policy.within.num_days()), (20, 30));
370/// ```
371#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
372#[serde(rename_all = "camelCase")]
373#[non_exhaustive]
374pub struct PromotionPolicy {
375    /// Unchanged approvals in a row a promotion needs.
376    pub approvals: usize,
377    /// The window they fall within.
378    #[serde(rename = "withinMs", with = "chrono_millis")]
379    pub within: Duration,
380}
381
382impl PromotionPolicy {
383    /// A policy of `approvals` within `within`.
384    pub fn new(approvals: usize, within: Duration) -> Self {
385        Self { approvals, within }
386    }
387}
388
389impl Default for PromotionPolicy {
390    fn default() -> Self {
391        Self { approvals: 20, within: Duration::days(30) }
392    }
393}
394
395mod chrono_millis {
396    use serde::{Deserialize, Deserializer, Serializer};
397
398    pub(super) fn serialize<S: Serializer>(
399        value: &chrono::Duration,
400        s: S,
401    ) -> Result<S::Ok, S::Error> {
402        s.serialize_i64(value.num_milliseconds())
403    }
404
405    pub(super) fn deserialize<'de, D: Deserializer<'de>>(
406        d: D,
407    ) -> Result<chrono::Duration, D::Error> {
408        Ok(chrono::Duration::milliseconds(i64::deserialize(d)?))
409    }
410}
411
412/// Every job's autonomy, its history and the owner's decisions on its proposals (spec 3.5
413/// §7.11), on in-memory, SQLite, PostgreSQL and Redis.
414///
415/// [`apply`](Self::apply) is a compare-and-set on the job's revision, so two replicas
416/// changing one job move it once.
417#[async_trait]
418pub trait AutonomyStore: Send + Sync {
419    /// The job's autonomy, or `None` for a job never registered.
420    ///
421    /// # Errors
422    ///
423    /// Returns [`KernelError::Store`] when the backend fails.
424    async fn get(&self, site: Uuid, job: &str) -> Result<Option<JobAutonomy>>;
425
426    /// Every job of the site, by job id.
427    ///
428    /// # Errors
429    ///
430    /// Returns [`KernelError::Store`] when the backend fails.
431    async fn list(&self, site: Uuid) -> Result<Vec<JobAutonomy>>;
432
433    /// Writes `record` and appends `change` when `record.revision` is one past the stored
434    /// revision (1 for a job with none) and `change` makes that revision; `false`, writing
435    /// nothing, otherwise.
436    ///
437    /// # Errors
438    ///
439    /// Returns [`KernelError::Config`] when `change` does not match `record`, or
440    /// [`KernelError::Store`] when the backend fails.
441    async fn apply(&self, record: JobAutonomy, change: AutonomyChange) -> Result<bool>;
442
443    /// The job's changes, oldest first.
444    ///
445    /// # Errors
446    ///
447    /// Returns [`KernelError::Store`] when the backend fails.
448    async fn history(&self, site: Uuid, job: &str) -> Result<Vec<AutonomyChange>>;
449
450    /// Records `decision`; `false` when the job already has a decision with its id.
451    ///
452    /// # Errors
453    ///
454    /// Returns [`KernelError::Store`] when the backend fails.
455    async fn record_decision(&self, decision: JobDecision) -> Result<bool>;
456
457    /// The job's decisions made at or after `since`, oldest first (by time, then id).
458    ///
459    /// # Errors
460    ///
461    /// Returns [`KernelError::Store`] when the backend fails.
462    async fn decisions(
463        &self,
464        site: Uuid,
465        job: &str,
466        since: DateTime<Utc>,
467    ) -> Result<Vec<JobDecision>>;
468}
469
470/// Refuses an `apply` whose change does not describe its record.
471pub(crate) fn check_apply(record: &JobAutonomy, change: &AutonomyChange) -> Result<()> {
472    if record.site != change.site
473        || record.job != change.job
474        || record.revision != change.revision
475        || record.level != change.to
476        || record.revision == 0
477    {
478        return Err(KernelError::Config {
479            reason: format!(
480                "an autonomy change of job {} must make the record's revision {} and level",
481                record.job, record.revision
482            ),
483        });
484    }
485    Ok(())
486}
487
488/// The autonomy ladder of a site's jobs (spec 3.5 §7.11, A-I13): promotion only by an
489/// owner's decision, demotion one level by the site on a guardrail breach, two owner
490/// rejections in a row, or an incident in the job's area, each with its reason.
491///
492/// | Call | Who | Effect |
493/// |---|---|---|
494/// | [`register`](Self::register), [`sync`](Self::sync) | the site | A job enters at its charter level; a charter that sets a lower level lowers it; a higher one changes nothing |
495/// | [`promote`](Self::promote), [`promote_to`](Self::promote_to) | an owner, with an [`OwnerDecision`] | One level up, or to a named higher level; refused for anyone else |
496/// | [`lower`](Self::lower) | the site | One level down |
497/// | [`guardrail_breach`](Self::guardrail_breach), [`incident`](Self::incident) | the site | One level down |
498/// | [`record_decision`](Self::record_decision) | the owner's inbox | Counts towards promotion; the second rejection in a row lowers one level |
499/// | [`eligibility`](Self::eligibility), [`offers`](Self::offers) | the weekly review | The promotions the record earned |
500///
501/// A promotion's change carries the owner's decision, from which the harness creates the
502/// standing rule (spec 3.5 §6 D-7). Every change is audited as `website.job.promoted` or
503/// `website.job.demoted` and emitted as [`CharterEvent::AutonomyChanged`].
504///
505/// # Example
506///
507/// ```rust
508/// use std::sync::Arc;
509/// use adk_core::principal::SubjectRef;
510/// use adk_kernel::charter::{AutonomyLadder, InMemoryAutonomyStore, OwnerDecision};
511/// use awp_types::AutonomyLevel;
512///
513/// # #[tokio::main(flavor = "current_thread")]
514/// # async fn main() -> adk_kernel::Result<()> {
515/// let ladder = AutonomyLadder::new(Arc::new(InMemoryAutonomyStore::new()));
516/// let site = uuid::Uuid::nil();
517/// ladder.register(site, "review-replies", AutonomyLevel::Propose, Some("serve")).await?;
518/// let agent = OwnerDecision::new("d-1", SubjectRef::service("urn:adk:agent:example/steward"), chrono::Utc::now());
519/// assert!(ladder.promote(site, "review-replies", &agent).await.is_err(), "the site never raises itself");
520/// let owner = OwnerDecision::new("d-2", SubjectRef::human("amina"), chrono::Utc::now());
521/// assert_eq!(ladder.promote(site, "review-replies", &owner).await?.level, AutonomyLevel::ActWithApproval);
522/// assert_eq!(ladder.guardrail_breach(site, "review-replies", "complaints").await?.unwrap().level, AutonomyLevel::Propose);
523/// # Ok(())
524/// # }
525/// ```
526#[derive(Clone)]
527pub struct AutonomyLadder {
528    store: Arc<dyn AutonomyStore>,
529    charters: Option<Arc<dyn CharterStore>>,
530    policy: PromotionPolicy,
531    clock: Arc<dyn Clock>,
532    audit: Option<AuditTrail>,
533    events: Option<Arc<dyn CharterEventSink>>,
534}
535
536impl std::fmt::Debug for AutonomyLadder {
537    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
538        f.debug_struct("AutonomyLadder")
539            .field("policy", &self.policy)
540            .field("charters", &self.charters.is_some())
541            .finish_non_exhaustive()
542    }
543}
544
545/// The subject the site's own demotions are recorded under.
546const SITE_SUBJECT: &str = "kernel:autonomy";
547
548/// How many times a change is retried against concurrent writers.
549const RETRIES: usize = 8;
550
551impl AutonomyLadder {
552    /// A ladder over `store` with the default promotion policy, no charter store (an owner
553    /// decision is then checked for a person only), the system clock, no audit and no events.
554    pub fn new(store: Arc<dyn AutonomyStore>) -> Self {
555        Self {
556            store,
557            charters: None,
558            policy: PromotionPolicy::default(),
559            clock: Arc::new(SystemClock),
560            audit: None,
561            events: None,
562        }
563    }
564
565    /// Checks owner decisions against the governance of the charter in force: the decider
566    /// must hold the owner role.
567    #[must_use]
568    pub fn with_charters(mut self, charters: Arc<dyn CharterStore>) -> Self {
569        self.charters = Some(charters);
570        self
571    }
572
573    /// Sets the promotion policy.
574    #[must_use]
575    pub fn with_policy(mut self, policy: PromotionPolicy) -> Self {
576        self.policy = policy;
577        self
578    }
579
580    /// Reads time from `clock`.
581    #[must_use]
582    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
583        self.clock = clock;
584        self
585    }
586
587    /// Audits every change on `trail`.
588    #[must_use]
589    pub fn with_audit(mut self, trail: AuditTrail) -> Self {
590        self.audit = Some(trail);
591        self
592    }
593
594    /// Emits every change on `sink`.
595    #[must_use]
596    pub fn with_events(mut self, sink: Arc<dyn CharterEventSink>) -> Self {
597        self.events = Some(sink);
598        self
599    }
600
601    /// The store.
602    pub fn store(&self) -> &Arc<dyn AutonomyStore> {
603        &self.store
604    }
605
606    /// The promotion policy.
607    pub fn policy(&self) -> &PromotionPolicy {
608        &self.policy
609    }
610
611    /// Registers `job` at `level` in `area` unless it is registered; returns its record.
612    ///
613    /// # Errors
614    ///
615    /// Returns a store error.
616    pub async fn register(
617        &self,
618        site: Uuid,
619        job: &str,
620        level: AutonomyLevel,
621        area: Option<&str>,
622    ) -> Result<JobAutonomy> {
623        self.enter(site, job, level, area, None).await
624    }
625
626    async fn enter(
627        &self,
628        site: Uuid,
629        job: &str,
630        level: AutonomyLevel,
631        area: Option<&str>,
632        charter_version: Option<u32>,
633    ) -> Result<JobAutonomy> {
634        if let Some(existing) = self.store.get(site, job).await? {
635            return Ok(existing);
636        }
637        let now = self.clock.now();
638        let mut record = JobAutonomy::new(site, job, level, now);
639        record.area = area.map(str::to_string);
640        let change = AutonomyChange {
641            site,
642            job: job.to_string(),
643            revision: 1,
644            from: None,
645            to: level,
646            reason: AutonomyReason::Initial { charter_version },
647            by: SubjectRef::service(SITE_SUBJECT),
648            at: now,
649        };
650        if self.store.apply(record.clone(), change).await? {
651            return Ok(record);
652        }
653        self.store.get(site, job).await?.ok_or_else(|| missing(job))
654    }
655
656    /// Brings the jobs of `charter`'s authority onto the ladder (spec 3.5 §7.11): a job not
657    /// registered enters at the charter's level; a registered job above the charter's level
658    /// is lowered to it, unless an owner promoted it there after the charter took effect; a
659    /// job below it stays where it is, since only an owner's [`promote`](Self::promote)
660    /// raises a level.
661    ///
662    /// The charter took effect when its owner signed it — the committing decision's time —
663    /// or, for an unsigned charter, when the charter store committed it; a charter with
664    /// neither lowers every job above it.
665    /// Syncing the charter in force again — as every start of a site does — so keeps the
666    /// owner's promotions (A-I13), and a later charter that sets a lower level still lowers.
667    ///
668    /// # Errors
669    ///
670    /// Returns a store error.
671    pub async fn sync(&self, charter: &Charter) -> Result<Vec<JobAutonomy>> {
672        let effective = match (&charter.signed, &self.charters) {
673            (Some(signature), _) => Some(signature.signed_at),
674            (None, Some(charters)) => charters
675                .get(charter.site_id, charter.version)
676                .await?
677                .map(|version| version.committed_at),
678            (None, None) => None,
679        };
680        let mut jobs = Vec::new();
681        for authority in &charter.authority {
682            let record = self
683                .enter(
684                    charter.site_id,
685                    &authority.job,
686                    authority.level,
687                    None,
688                    Some(charter.version),
689                )
690                .await?;
691            let promoted = match effective {
692                Some(since) => {
693                    self.promoted_since(charter.site_id, &authority.job, record.level, since)
694                        .await?
695                }
696                None => false,
697            };
698            let record = if ladder_rank(record.level) > ladder_rank(authority.level) && !promoted {
699                let reason = AutonomyReason::Lowered {
700                    reason: format!("charter version {} sets it lower", charter.version),
701                };
702                self.change(
703                    charter.site_id,
704                    &authority.job,
705                    |_| Some(authority.level),
706                    reason,
707                    None,
708                )
709                .await?
710                .unwrap_or(record)
711            } else {
712                record
713            };
714            jobs.push(record);
715        }
716        Ok(jobs)
717    }
718
719    /// Whether an owner promoted `job` to `level` or above at or after `since`.
720    async fn promoted_since(
721        &self,
722        site: Uuid,
723        job: &str,
724        level: AutonomyLevel,
725        since: DateTime<Utc>,
726    ) -> Result<bool> {
727        Ok(self.store.history(site, job).await?.iter().any(|change| {
728            matches!(change.reason, AutonomyReason::Promoted { .. })
729                && change.at >= since
730                && ladder_rank(change.to) >= ladder_rank(level)
731        }))
732    }
733
734    /// The job's level, or `None` for a job never registered.
735    ///
736    /// # Errors
737    ///
738    /// Returns a store error.
739    pub async fn level(&self, site: Uuid, job: &str) -> Result<Option<AutonomyLevel>> {
740        Ok(self.store.get(site, job).await?.map(|record| record.level))
741    }
742
743    /// Raises `job` one level by `decision` (A-I13). See [`promote_to`](Self::promote_to).
744    ///
745    /// # Errors
746    ///
747    /// As [`promote_to`](Self::promote_to); also [`KernelError::Config`] at the top rung.
748    pub async fn promote(
749        &self,
750        site: Uuid,
751        job: &str,
752        decision: &OwnerDecision,
753    ) -> Result<JobAutonomy> {
754        let record = self.store.get(site, job).await?.ok_or_else(|| missing(job))?;
755        let to = above(record.level).ok_or_else(|| KernelError::Config {
756            reason: format!("job {job} is at {:?}, the top of the ladder", record.level),
757        })?;
758        self.promote_to(site, job, to, decision).await
759    }
760
761    /// Raises `job` to `to` by `decision` (spec 3.5 §7.11, A-I13). The decision must be a
762    /// person's ([`OwnerDecision::check_person`]); with a charter store, that person must hold
763    /// the owner role in the charter in force. The change carries the decision, from which
764    /// the harness creates the standing rule.
765    ///
766    /// # Errors
767    ///
768    /// Returns [`KernelError::Unauthorized`] for a decision no owner made,
769    /// [`KernelError::Config`] when `to` is not above the job's level, or a store error.
770    pub async fn promote_to(
771        &self,
772        site: Uuid,
773        job: &str,
774        to: AutonomyLevel,
775        decision: &OwnerDecision,
776    ) -> Result<JobAutonomy> {
777        decision.check_person()?;
778        if let Some(charters) = &self.charters {
779            let current =
780                charters.current(site).await?.ok_or_else(|| KernelError::Unauthorized {
781                    reason: format!(
782                        "site {site} has no charter, so it has no owner to promote {job}"
783                    ),
784                })?;
785            if !current.charter.governance.holds(&decision.owner.id, Role::Owner) {
786                return Err(KernelError::Unauthorized {
787                    reason: format!(
788                        "{} is not an owner in charter version {} of site {site}, so cannot \
789                         promote {job} (A-I13)",
790                        decision.owner.id,
791                        current.version()
792                    ),
793                });
794            }
795        }
796        let reason = AutonomyReason::Promoted { decision: decision.clone() };
797        let changed = self
798            .change(
799                site,
800                job,
801                |level| (ladder_rank(to) > ladder_rank(level)).then_some(to),
802                reason,
803                Some(decision.owner.clone()),
804            )
805            .await?;
806        changed.ok_or_else(|| KernelError::Config {
807            reason: format!("job {job} is not below {to:?}, so there is nothing to promote"),
808        })
809    }
810
811    /// Lowers `job` one level for `reason` (spec 3.5 §7.11): the site may always lower its
812    /// own autonomy. `None` when the job is at Observe already.
813    ///
814    /// # Errors
815    ///
816    /// Returns [`KernelError::Config`] for an unregistered job, or a store error.
817    pub async fn lower(&self, site: Uuid, job: &str, reason: &str) -> Result<Option<JobAutonomy>> {
818        self.demote(site, job, AutonomyReason::Lowered { reason: reason.to_string() }).await
819    }
820
821    /// Lowers `job` one level because `guardrail` was breached (spec 3.5 §7.11, A-I15).
822    ///
823    /// # Errors
824    ///
825    /// Returns [`KernelError::Config`] for an unregistered job, or a store error.
826    pub async fn guardrail_breach(
827        &self,
828        site: Uuid,
829        job: &str,
830        guardrail: &str,
831    ) -> Result<Option<JobAutonomy>> {
832        self.demote(site, job, AutonomyReason::GuardrailBreach { guardrail: guardrail.into() })
833            .await
834    }
835
836    /// Lowers every job of `area` one level for `incident` (spec 3.5 §7.11); returns the
837    /// jobs it lowered.
838    ///
839    /// # Errors
840    ///
841    /// Returns a store error.
842    pub async fn incident(
843        &self,
844        site: Uuid,
845        area: &str,
846        incident: &str,
847    ) -> Result<Vec<JobAutonomy>> {
848        let mut lowered = Vec::new();
849        for job in self.store.list(site).await? {
850            if job.area.as_deref() != Some(area) {
851                continue;
852            }
853            let reason =
854                AutonomyReason::Incident { area: area.to_string(), incident: incident.to_string() };
855            if let Some(record) = self.demote(site, &job.job, reason).await? {
856                lowered.push(record);
857            }
858        }
859        Ok(lowered)
860    }
861
862    /// Records the owner's `decision` on a proposal of its job (spec 3.5 §7.11). The second
863    /// rejection in a row since the job's last change lowers it one level, which is
864    /// returned. A repeated decision id changes nothing.
865    ///
866    /// # Errors
867    ///
868    /// Returns [`KernelError::Unauthorized`] for a decision no person made — an agent's
869    /// approvals never build a promotion — [`KernelError::Config`] for an unregistered job,
870    /// or a store error.
871    pub async fn record_decision(&self, decision: JobDecision) -> Result<Option<JobAutonomy>> {
872        if decision.by.kind != SubjectKind::Human || is_agent_principal(&decision.by.id) {
873            return Err(KernelError::Unauthorized {
874                reason: format!(
875                    "{} is not a person; only the owner's decisions count towards a job's \
876                     autonomy (A-I13)",
877                    decision.by.id
878                ),
879            });
880        }
881        let (site, job) = (decision.site, decision.job.clone());
882        let record = self.store.get(site, &job).await?.ok_or_else(|| missing(&job))?;
883        if !self.store.record_decision(decision.clone()).await?
884            || decision.outcome != DecisionOutcome::Rejected
885        {
886            return Ok(None);
887        }
888        let recent = self.store.decisions(site, &job, record.since).await?;
889        let last_two: Vec<&JobDecision> = recent.iter().rev().take(2).collect();
890        if last_two.len() == 2 && last_two.iter().all(|d| d.outcome == DecisionOutcome::Rejected) {
891            let decisions = last_two.iter().rev().map(|d| d.id.clone()).collect();
892            return self.demote(site, &job, AutonomyReason::OwnerRejections { decisions }).await;
893        }
894        Ok(None)
895    }
896
897    /// Whether `job` has earned a promotion (spec 3.5 §7.11): the unchanged approvals in a
898    /// row, latest first, made within the policy's window since the job's last change.
899    ///
900    /// # Errors
901    ///
902    /// Returns [`KernelError::Config`] for an unregistered job, or a store error.
903    pub async fn eligibility(&self, site: Uuid, job: &str) -> Result<PromotionEligibility> {
904        let record = self.store.get(site, job).await?.ok_or_else(|| missing(job))?;
905        let window_start = self.clock.now() - self.policy.within;
906        let since = record.since.max(window_start);
907        let decisions = self.store.decisions(site, job, since).await?;
908        let streak = decisions
909            .iter()
910            .rev()
911            .take_while(|decision| decision.outcome == DecisionOutcome::ApprovedUnchanged)
912            .count();
913        let next = above(record.level);
914        Ok(PromotionEligibility {
915            site,
916            job: job.to_string(),
917            level: record.level,
918            next,
919            streak,
920            needed: self.policy.approvals,
921            eligible: next.is_some() && streak >= self.policy.approvals,
922        })
923    }
924
925    /// The promotions the site's jobs earned, for the weekly review; each is emitted as
926    /// [`CharterEvent::PromotionOffered`].
927    ///
928    /// # Errors
929    ///
930    /// Returns a store error.
931    pub async fn offers(&self, site: Uuid) -> Result<Vec<PromotionEligibility>> {
932        let mut offers = Vec::new();
933        for job in self.store.list(site).await? {
934            let eligibility = self.eligibility(site, &job.job).await?;
935            if let (true, Some(to)) = (eligibility.eligible, eligibility.next) {
936                emit(
937                    self.events.as_ref(),
938                    CharterEvent::PromotionOffered {
939                        site,
940                        job: job.job.clone(),
941                        to,
942                        streak: eligibility.streak,
943                        at: self.clock.now(),
944                    },
945                )
946                .await;
947                offers.push(eligibility);
948            }
949        }
950        Ok(offers)
951    }
952
953    /// Lowers `job` one rung for `reason`; `None` at Observe.
954    async fn demote(
955        &self,
956        site: Uuid,
957        job: &str,
958        reason: AutonomyReason,
959    ) -> Result<Option<JobAutonomy>> {
960        if self.store.get(site, job).await?.is_none() {
961            return Err(missing(job));
962        }
963        self.change(site, job, below, reason, None).await
964    }
965
966    /// Moves `job` to `target(level)` for `reason`, retrying against concurrent changes;
967    /// `None` when `target` leaves it where it is. `by` is the owner for a promotion, the
968    /// site otherwise.
969    async fn change(
970        &self,
971        site: Uuid,
972        job: &str,
973        target: impl Fn(AutonomyLevel) -> Option<AutonomyLevel>,
974        reason: AutonomyReason,
975        by: Option<SubjectRef>,
976    ) -> Result<Option<JobAutonomy>> {
977        for _ in 0..RETRIES {
978            let current = self.store.get(site, job).await?.ok_or_else(|| missing(job))?;
979            let Some(to) = target(current.level).filter(|to| *to != current.level) else {
980                return Ok(None);
981            };
982            let now = self.clock.now();
983            let next = JobAutonomy {
984                level: to,
985                since: now,
986                revision: current.revision + 1,
987                ..current.clone()
988            };
989            let by = by.clone().unwrap_or_else(|| SubjectRef::service(SITE_SUBJECT));
990            let change = AutonomyChange {
991                site,
992                job: job.to_string(),
993                revision: next.revision,
994                from: Some(current.level),
995                to,
996                reason: reason.clone(),
997                by: by.clone(),
998                at: now,
999            };
1000            if self.store.apply(next.clone(), change).await? {
1001                let raised = ladder_rank(to) > ladder_rank(current.level);
1002                tracing::info!(site = %site, job, from = ?current.level, to = ?to, reason = %reason.describe(), "job autonomy changed");
1003                let decision = match &reason {
1004                    AutonomyReason::Promoted { decision } => Some(decision.decision_id.clone()),
1005                    _ => None,
1006                };
1007                record(
1008                    self.audit.as_ref(),
1009                    WEBSITE_AUDIT_KIND,
1010                    if raised { audit::JOB_PROMOTED } else { audit::JOB_DEMOTED },
1011                    AuditActor::subject(by),
1012                    json!({
1013                        "site": site,
1014                        "job": job,
1015                        "from": current.level,
1016                        "to": to,
1017                        "reason": reason.describe(),
1018                        "decision": decision,
1019                    }),
1020                )
1021                .await;
1022                emit(
1023                    self.events.as_ref(),
1024                    CharterEvent::AutonomyChanged {
1025                        site,
1026                        job: job.to_string(),
1027                        from: current.level,
1028                        to,
1029                        reason: reason.describe(),
1030                        at: now,
1031                    },
1032                )
1033                .await;
1034                return Ok(Some(next));
1035            }
1036        }
1037        Err(KernelError::Store {
1038            backend: "autonomy",
1039            reason: format!("job {job} kept changing under {RETRIES} attempts; try again"),
1040        })
1041    }
1042}
1043
1044fn missing(job: &str) -> KernelError {
1045    KernelError::Config {
1046        reason: format!(
1047            "job {job} is not on the autonomy ladder; register it from the charter's authority \
1048             first"
1049        ),
1050    }
1051}