Skip to main content

adk_harness/website/
ladder.rs

1//! The autonomy ladder compiled to harness policy (spec 3.5 §7.11, D-7, A-I13, A-I15).
2//!
3//! | Level | Harness mode of the job's agent | Website tools of the job |
4//! |---|---|---|
5//! | Observe | read-only | read-only tools only; output goes to reports |
6//! | Propose | plan | read-only tools, drafts and decision cards; everything else is proposed as a draft or an agenda item |
7//! | Act with approval | ask | every other call is held through the approval service |
8//! | Act, reversible only | auto | drafts, a rollback to a signed release and the edge's read-only switch run; every other call is held |
9//! | Act within budget | auto | drafts and reversible acts run; every other call runs within `DeclarativePolicy` rules (`for_agent`, `at_most`) and a `RunBudget`, and is held beyond them |
10//!
11//! A level above Propose lets a call run only through a standing rule the owner's decision
12//! created (A-I13): [`promote_job`] makes those rules from an `OwnerDecision`, and the site
13//! can only lower a level ([`apply_demotion`] revokes them). The ladder policy reads each
14//! job's level from the kernel's `AutonomyStore` at every call, so a demotion applies to the
15//! next call with its reason.
16
17use std::collections::{BTreeMap, BTreeSet};
18use std::sync::Arc;
19
20use adk_core::principal::SubjectKind;
21use adk_core::{
22    ArgPredicate, DeclarativePolicy, PolicyDecision, PolicyRule, RunBudget, STATIC_TOOL_ORIGIN,
23    StrictestPolicy, ToolEffect, ToolPolicy, ToolPolicyRequest,
24};
25use adk_kernel::charter::{
26    AutonomyLadder, AutonomyStore, JobAutonomy, JobPauses, OwnerDecision, ladder_rank,
27};
28use async_trait::async_trait;
29use awp_types::{AutonomyLevel, Charter};
30use uuid::Uuid;
31
32use super::catalog::{self, BACK_OFFICE_ORIGIN, Hold, ToolSpec, WebsitePartition};
33use super::site::{SiteRef, kernel_error};
34use crate::approvals::matcher::glob_matches;
35use crate::approvals::{OriginPin, RuleScope, StandingDecision, StandingRule, StandingRuleStore};
36use crate::mode::HarnessMode;
37
38/// What a level decides for one call, before budgets (spec 3.5 §7.11 table).
39#[derive(Clone, Debug, PartialEq, Eq)]
40pub enum LevelDecision {
41    /// The call runs.
42    Allow,
43    /// The call is refused, with why.
44    Deny(String),
45    /// The call is held for a person, with why.
46    Hold(String),
47    /// The job's within-budget rules decide.
48    WithinBudget,
49}
50
51/// The §7.11 table for one call: the decision `level` gives a tool whose catalogue entry is
52/// `spec` (`None` for a tool outside the catalogue) and whose declared effect is `effect`.
53///
54/// # Example
55///
56/// ```rust
57/// use adk_core::ToolEffect;
58/// use adk_harness::website::{LevelDecision, SITE_ROLLBACK, level_decision, spec};
59/// use awp_types::AutonomyLevel;
60///
61/// let rollback = spec(SITE_ROLLBACK);
62/// assert!(matches!(level_decision(AutonomyLevel::Propose, rollback, ToolEffect::NonIdempotent), LevelDecision::Deny(_)));
63/// assert!(matches!(level_decision(AutonomyLevel::ActWithApproval, rollback, ToolEffect::NonIdempotent), LevelDecision::Hold(_)));
64/// assert_eq!(level_decision(AutonomyLevel::ActReversibleOnly, rollback, ToolEffect::NonIdempotent), LevelDecision::Allow);
65/// ```
66pub fn level_decision(
67    level: AutonomyLevel,
68    spec: Option<&ToolSpec>,
69    effect: ToolEffect,
70) -> LevelDecision {
71    let effect = spec.map_or(effect, |spec| spec.effect);
72    if effect == ToolEffect::ReadOnly {
73        return LevelDecision::Allow;
74    }
75    // A decision card proposes to the owner, as a draft does; the website policy holds it.
76    let draft = spec.is_some_and(|spec| spec.draft || spec.hold == Hold::Always);
77    let reversible = spec.is_some_and(|spec| spec.reversible);
78    match level {
79        AutonomyLevel::Observe => LevelDecision::Deny(
80            "the job is at Observe: it reads and reports, and changes nothing".into(),
81        ),
82        AutonomyLevel::Propose if draft => LevelDecision::Allow,
83        AutonomyLevel::Propose => LevelDecision::Deny(
84            "the job is at Propose: draft the change or propose it as an agenda item for the \
85             owner"
86                .into(),
87        ),
88        AutonomyLevel::ActWithApproval if draft => LevelDecision::Allow,
89        AutonomyLevel::ActWithApproval => {
90            LevelDecision::Hold("the job acts with the owner's approval of each change".into())
91        }
92        AutonomyLevel::ActReversibleOnly if draft || reversible => LevelDecision::Allow,
93        AutonomyLevel::ActReversibleOnly => LevelDecision::Hold(
94            "the job acts alone only where the act is reversible: drafts, a rollback to a \
95             signed release and the edge's read-only switch"
96                .into(),
97        ),
98        AutonomyLevel::ActWithinBudget if draft || reversible => LevelDecision::Allow,
99        AutonomyLevel::ActWithinBudget => LevelDecision::WithinBudget,
100        _ => LevelDecision::Deny("the job's autonomy level is unknown to this harness".into()),
101    }
102}
103
104/// The harness mode of an agent whose loosest job is at `level` (spec 3.5 §7.11).
105///
106/// # Example
107///
108/// ```rust
109/// use adk_harness::HarnessMode;
110/// use adk_harness::website::mode_for_level;
111/// use awp_types::AutonomyLevel;
112///
113/// assert_eq!(mode_for_level(AutonomyLevel::Observe), HarnessMode::ReadOnly);
114/// assert_eq!(mode_for_level(AutonomyLevel::Propose), HarnessMode::Plan);
115/// assert_eq!(mode_for_level(AutonomyLevel::ActWithApproval), HarnessMode::Ask);
116/// assert_eq!(mode_for_level(AutonomyLevel::ActWithinBudget), HarnessMode::Auto);
117/// ```
118pub fn mode_for_level(level: AutonomyLevel) -> HarnessMode {
119    match level {
120        AutonomyLevel::Observe => HarnessMode::ReadOnly,
121        AutonomyLevel::Propose => HarnessMode::Plan,
122        AutonomyLevel::ActWithApproval => HarnessMode::Ask,
123        _ => HarnessMode::Auto,
124    }
125}
126
127/// A job's agent, tools and within-budget bounds (spec 3.5 §7.11, §7.20).
128///
129/// # Example
130///
131/// ```rust
132/// use adk_core::ArgPredicate;
133/// use adk_harness::website::JobBinding;
134///
135/// let finance = JobBinding::new("running-costs", "finance", ["wallet_pay"])
136///     .within("wallet_pay", ArgPredicate::at_most("/amount", 5_000.0));
137/// assert_eq!(finance.agent, "finance");
138/// ```
139#[derive(Clone, Debug, PartialEq)]
140pub struct JobBinding {
141    /// The job's id, as the charter's authority names it.
142    pub job: String,
143    /// The agent that does it.
144    pub agent: String,
145    /// Globs over the names of the tools that are the job's.
146    pub tools: Vec<String>,
147    /// The area of its work, which an incident's demotion matches (§7.20).
148    pub area: Option<String>,
149    /// Bounds within budget: a tool glob and a predicate its calls must satisfy to run alone.
150    pub predicates: Vec<(String, ArgPredicate)>,
151    /// The run budget under "act within budget".
152    pub run_budget: Option<RunBudget>,
153    /// The origins of tools outside the catalogue, by name; `static` by default.
154    pub origins: BTreeMap<String, String>,
155}
156
157impl JobBinding {
158    /// Job `job`, done by `agent` with `tools`.
159    pub fn new(
160        job: impl Into<String>,
161        agent: impl Into<String>,
162        tools: impl IntoIterator<Item = impl Into<String>>,
163    ) -> Self {
164        Self {
165            job: job.into(),
166            agent: agent.into(),
167            tools: tools.into_iter().map(Into::into).collect(),
168            area: None,
169            predicates: Vec::new(),
170            run_budget: None,
171            origins: BTreeMap::new(),
172        }
173    }
174
175    /// Sets the area.
176    #[must_use]
177    pub fn in_area(mut self, area: impl Into<String>) -> Self {
178        self.area = Some(area.into());
179        self
180    }
181
182    /// Bounds the calls of `tool` (a glob) within budget by `predicate`.
183    #[must_use]
184    pub fn within(mut self, tool: impl Into<String>, predicate: ArgPredicate) -> Self {
185        self.predicates.push((tool.into(), predicate));
186        self
187    }
188
189    /// Sets the run budget.
190    #[must_use]
191    pub fn with_run_budget(mut self, budget: RunBudget) -> Self {
192        self.run_budget = Some(budget);
193        self
194    }
195
196    /// Names the origin of `tool`, a tool outside the catalogue, such as a driver's.
197    #[must_use]
198    pub fn with_origin(mut self, tool: impl Into<String>, origin: impl Into<String>) -> Self {
199        self.origins.insert(tool.into(), origin.into());
200        self
201    }
202
203    /// Whether `tool` is one of the job's.
204    pub fn covers(&self, tool: &str) -> bool {
205        self.tools.iter().any(|pattern| glob_matches(pattern, tool))
206    }
207
208    fn origin_of(&self, tool: &str) -> String {
209        match catalog::spec(tool) {
210            Some(spec)
211                if spec.partition == WebsitePartition::BackOffice
212                    && tool != catalog::WALLET_PAY =>
213            {
214                BACK_OFFICE_ORIGIN.to_string()
215            }
216            _ => self.origins.get(tool).cloned().unwrap_or_else(|| STATIC_TOOL_ORIGIN.to_string()),
217        }
218    }
219}
220
221/// Compiles a site's jobs to harness policy (spec 3.5 §7.11): the agent's mode, the ladder
222/// policy, the within-budget rules, the standing rules an owner's decision creates and the
223/// job pauses a guardrail breach applies (A-I15).
224#[derive(Clone, Debug)]
225pub struct LadderCompiler {
226    site: SiteRef,
227    jobs: Vec<JobBinding>,
228}
229
230impl LadderCompiler {
231    /// A compiler for `site` with no jobs.
232    pub fn new(site: SiteRef) -> Self {
233        Self { site, jobs: Vec::new() }
234    }
235
236    /// Adds a job.
237    #[must_use]
238    pub fn job(mut self, binding: JobBinding) -> Self {
239        self.jobs.push(binding);
240        self
241    }
242
243    /// Adds `bindings` with the limits `charter` gives their jobs: a `spend_cap` bounds the
244    /// `/amount` of each of the job's financial calls, and `actions_per_day` caps the tool
245    /// calls of a run.
246    #[must_use]
247    pub fn with_charter(
248        mut self,
249        charter: &Charter,
250        bindings: impl IntoIterator<Item = JobBinding>,
251    ) -> Self {
252        for mut binding in bindings {
253            if let Some(authority) = charter.authority.iter().find(|a| a.job == binding.job) {
254                if let Some(cap) = authority.limits.spend_cap {
255                    let financial: Vec<&str> = catalog::CATALOG
256                        .iter()
257                        .filter(|spec| spec.class == adk_kernel::drivers::EffectClass::Financial)
258                        .filter(|spec| binding.covers(spec.name))
259                        .map(|spec| spec.name)
260                        .collect();
261                    for tool in financial {
262                        binding
263                            .predicates
264                            .push((tool.to_string(), ArgPredicate::at_most("/amount", cap as f64)));
265                    }
266                }
267                if let Some(actions) = authority.limits.actions_per_day {
268                    binding.run_budget = Some(
269                        binding.run_budget.unwrap_or_default().max_tool_calls(u64::from(actions)),
270                    );
271                }
272            }
273            self.jobs.push(binding);
274        }
275        self
276    }
277
278    /// Pins the origin of each of `tools` outside the catalogue — a driver's, the wallet's —
279    /// in every job that covers it, so the standing rules a promotion grants admit exactly
280    /// the publisher the agent is given (spec 3.5 §7.11, A-I13).
281    ///
282    /// # Example
283    ///
284    /// ```rust,ignore
285    /// let tools = email_tools(outbox, Side::BackOffice);
286    /// let compiler = LadderCompiler::new(site)
287    ///     .with_charter(&charter, bindings)
288    ///     .with_tool_origins(&tools);
289    /// ```
290    #[must_use]
291    pub fn with_tool_origins(mut self, tools: &[Arc<dyn adk_core::Tool>]) -> Self {
292        for binding in &mut self.jobs {
293            for tool in tools {
294                let name = tool.name();
295                let catalogued = catalog::spec(name).is_some_and(|spec| {
296                    spec.partition == WebsitePartition::BackOffice && name != catalog::WALLET_PAY
297                });
298                if !catalogued && binding.covers(name) {
299                    binding.origins.insert(name.to_string(), tool.origin().to_string());
300                }
301            }
302        }
303        self
304    }
305
306    /// The site.
307    pub fn site(&self) -> &SiteRef {
308        &self.site
309    }
310
311    /// The jobs.
312    pub fn jobs(&self) -> &[JobBinding] {
313        &self.jobs
314    }
315
316    /// The binding of `job`.
317    pub fn binding(&self, job: &str) -> Option<&JobBinding> {
318        self.jobs.iter().find(|binding| binding.job == job)
319    }
320
321    /// The harness mode of `agent` given its jobs' `levels` (spec 3.5 §7.11): the mode of
322    /// its loosest job; Propose's plan mode for an agent with no job.
323    pub fn mode_for_agent(
324        &self,
325        agent: &str,
326        levels: &BTreeMap<String, AutonomyLevel>,
327    ) -> HarnessMode {
328        self.jobs
329            .iter()
330            .filter(|binding| binding.agent == agent)
331            .map(|binding| levels.get(&binding.job).copied().unwrap_or(AutonomyLevel::Propose))
332            .max_by_key(|level| ladder_rank(*level))
333            .map_or(HarnessMode::Plan, mode_for_level)
334    }
335
336    /// The run budget of `agent` given its jobs' `levels`: the tightest tool-call cap of its
337    /// jobs acting within budget.
338    pub fn budget_for_agent(
339        &self,
340        agent: &str,
341        levels: &BTreeMap<String, AutonomyLevel>,
342    ) -> Option<RunBudget> {
343        self.jobs
344            .iter()
345            .filter(|binding| {
346                binding.agent == agent
347                    && levels.get(&binding.job) == Some(&AutonomyLevel::ActWithinBudget)
348            })
349            .filter_map(|binding| binding.run_budget.clone())
350            .min_by_key(|budget| budget.max_tool_calls.unwrap_or(u64::MAX))
351    }
352
353    /// The within-budget rules of `job` (spec 3.5 §7.11): for its agent's principal, a call
354    /// of a bounded tool runs when every bound holds and is held beyond them; any other tool
355    /// of the job runs.
356    pub fn declarative(&self, job: &str) -> Option<DeclarativePolicy> {
357        let binding = self.binding(job)?;
358        let principal = self.site.principal(&binding.agent);
359        let mut builder =
360            DeclarativePolicy::builder().name(format!("adk-harness.website.budget:{job}"));
361        let mut bounded: BTreeMap<&str, Vec<&ArgPredicate>> = BTreeMap::new();
362        for (tool, predicate) in &binding.predicates {
363            bounded.entry(tool.as_str()).or_default().push(predicate);
364        }
365        for (tool, predicates) in bounded {
366            let mut rule = PolicyRule::allow(tool).for_agent(principal.clone());
367            for predicate in predicates {
368                rule = rule.when(predicate.clone());
369            }
370            builder = builder.rule(rule).rule(
371                PolicyRule::require_approval(
372                    tool,
373                    format!("beyond job {job}'s budget; the owner decides this one"),
374                )
375                .for_agent(principal.clone()),
376            );
377        }
378        for tool in &binding.tools {
379            builder = builder.rule(PolicyRule::allow(tool.clone()).for_agent(principal.clone()));
380        }
381        Some(builder.build())
382    }
383
384    /// The standing rules `job` holds at `level` (spec 3.5 §7.11, A-I13): the tools of the
385    /// job an owner's decision lets past the harness's mode.
386    ///
387    /// | Level | Tools |
388    /// |---|---|
389    /// | Observe, Propose | none: drafts and decision cards need no rule |
390    /// | Act with approval | every tool of the job that is not read-only, a draft or a decision card; the ladder still holds each of their calls for the owner, so the rules record what the owner granted |
391    /// | Act, reversible only | its reversible acts: a rollback to a signed release and the edge's read-only switch (A-I11) |
392    /// | Act within budget | every tool of the job that is not read-only, a draft or a decision card |
393    pub fn rule_tools(&self, job: &str, level: AutonomyLevel) -> Vec<String> {
394        let Some(binding) = self.binding(job) else { return Vec::new() };
395        let every =
396            matches!(level, AutonomyLevel::ActWithApproval | AutonomyLevel::ActWithinBudget);
397        let mut names: BTreeSet<String> = BTreeSet::new();
398        for pattern in &binding.tools {
399            let catalogued: Vec<&ToolSpec> = catalog::CATALOG
400                .iter()
401                .filter(|spec| {
402                    spec.partition == WebsitePartition::BackOffice
403                        && glob_matches(pattern, spec.name)
404                })
405                .collect();
406            if catalogued.is_empty() && every {
407                names.insert(pattern.clone());
408            }
409            for spec in catalogued {
410                let needs_rule =
411                    spec.effect != ToolEffect::ReadOnly && !spec.draft && spec.hold != Hold::Always;
412                let allowed = match level {
413                    AutonomyLevel::ActReversibleOnly => spec.reversible,
414                    _ => every,
415                };
416                if needs_rule && allowed {
417                    names.insert(spec.name.to_string());
418                }
419            }
420        }
421        names.into_iter().collect()
422    }
423
424    fn rule_id(&self, job: &str, tool: &str, kind: SubjectKind) -> String {
425        let kind = match kind {
426            SubjectKind::Human => "human",
427            SubjectKind::Service => "service",
428            _ => "other",
429        };
430        format!("website:{}:{job}:{tool}:{kind}", self.site.name)
431    }
432
433    /// The standing rules that let `job` act at `level`, created by the owner's `decision`
434    /// for the runs of `user` (spec 3.5 §7.11, A-I13): one per tool and subject kind (the
435    /// owner's own turns and the kernel's scheduled ones), pinned to the tool's origin and
436    /// the job's agent.
437    pub fn standing_rules(
438        &self,
439        job: &str,
440        level: AutonomyLevel,
441        decision: &OwnerDecision,
442        user: &str,
443    ) -> Vec<StandingRule> {
444        let Some(binding) = self.binding(job) else { return Vec::new() };
445        let mut rules = Vec::new();
446        for tool in self.rule_tools(job, level) {
447            for kind in [SubjectKind::Human, SubjectKind::Service] {
448                rules.push(StandingRule {
449                    id: self.rule_id(job, &tool, kind),
450                    scope: RuleScope::User {
451                        app_name: self.site.name.clone(),
452                        user_id: user.to_string(),
453                        subject_kind: kind,
454                    },
455                    tool: tool.clone(),
456                    origin: OriginPin::AnyDeclaration { source: binding.origin_of(&tool) },
457                    agent: Some(self.site.principal(&binding.agent)),
458                    predicates: Vec::new(),
459                    decision: StandingDecision::Allow,
460                    created_by: decision.owner.clone(),
461                    created_at: decision.at,
462                    expires_at: None,
463                    label: format!(
464                        "{tool} by {} for job {job} at {level:?} (owner decision {})",
465                        binding.agent, decision.decision_id
466                    ),
467                    source_fingerprint: None,
468                });
469            }
470        }
471        rules
472    }
473
474    /// Job pauses with every job mapped to its agent, by name and principal (A-I15).
475    pub fn job_pauses(&self) -> JobPauses {
476        self.jobs.iter().fold(JobPauses::new(), |pauses, binding| {
477            pauses
478                .with_agent(binding.job.clone(), binding.agent.clone())
479                .with_agent(binding.job.clone(), self.site.principal(&binding.agent))
480        })
481    }
482
483    /// The ladder policy over the jobs' levels in `store`, strictest with `pauses` (spec 3.5
484    /// §7.11, A-I15): put it on every back-office agent.
485    pub fn policy(
486        &self,
487        store: Arc<dyn AutonomyStore>,
488        pauses: Arc<JobPauses>,
489    ) -> Arc<dyn ToolPolicy> {
490        let budgets = self
491            .jobs
492            .iter()
493            .filter_map(|binding| Some((binding.job.clone(), self.declarative(&binding.job)?)))
494            .collect();
495        Arc::new(StrictestPolicy::new(vec![
496            Arc::new(LadderPolicy { compiler: self.clone(), store, budgets }),
497            pauses,
498        ]))
499    }
500}
501
502/// Decides each call by its job's level, read at every call (spec 3.5 §7.11).
503struct LadderPolicy {
504    compiler: LadderCompiler,
505    store: Arc<dyn AutonomyStore>,
506    budgets: BTreeMap<String, DeclarativePolicy>,
507}
508
509impl std::fmt::Debug for LadderPolicy {
510    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
511        f.debug_struct("LadderPolicy")
512            .field("site", &self.compiler.site.name)
513            .finish_non_exhaustive()
514    }
515}
516
517impl LadderPolicy {
518    fn agent_of(&self, request: &ToolPolicyRequest) -> Option<String> {
519        let id = request.acting.as_ref().map(|acting| acting.agent.id.as_str().to_string());
520        self.compiler
521            .jobs
522            .iter()
523            .find(|binding| {
524                binding.agent == request.agent_name
525                    || id.as_deref() == Some(self.compiler.site.principal(&binding.agent).as_str())
526            })
527            .map(|binding| binding.agent.clone())
528    }
529
530    async fn level(&self, job: &str) -> (AutonomyLevel, String) {
531        match self.store.get(self.compiler.site.id, job).await {
532            Ok(Some(record)) => {
533                let why = match self.store.history(self.compiler.site.id, job).await {
534                    Ok(history) => {
535                        history.last().map(|change| change.reason.describe()).unwrap_or_default()
536                    }
537                    Err(_) => String::new(),
538                };
539                (record.level, why)
540            }
541            Ok(None) => (
542                AutonomyLevel::Propose,
543                "no level recorded; every job proposes until the charter says otherwise".into(),
544            ),
545            Err(error) => {
546                tracing::warn!(error = %error, website.job = job, "autonomy store unavailable; deciding as Observe");
547                (AutonomyLevel::Observe, "the autonomy store is unavailable".into())
548            }
549        }
550    }
551}
552
553#[async_trait]
554impl ToolPolicy for LadderPolicy {
555    async fn evaluate(&self, request: &ToolPolicyRequest) -> PolicyDecision {
556        let spec = catalog::spec(&request.tool_name)
557            .filter(|spec| spec.partition == WebsitePartition::BackOffice);
558        let Some(agent) = self.agent_of(request) else {
559            return PolicyDecision::Allow;
560        };
561        let jobs: Vec<&JobBinding> = self
562            .compiler
563            .jobs
564            .iter()
565            .filter(|binding| binding.agent == agent && binding.covers(&request.tool_name))
566            .collect();
567        if jobs.is_empty() {
568            return match spec {
569                Some(spec) if spec.effect != ToolEffect::ReadOnly => PolicyDecision::deny(format!(
570                    "no job of {agent} covers {}; the charter gives it no authority for it",
571                    request.tool_name
572                )),
573                _ => PolicyDecision::Allow,
574            };
575        }
576        // A call that names its job is decided at that job's level; otherwise at the
577        // strictest level of the jobs it could belong to. A promotion request's `job` is the
578        // job it asks about, not the one asking.
579        let named = request
580            .args
581            .get("job")
582            .and_then(serde_json::Value::as_str)
583            .filter(|_| request.tool_name != catalog::JOB_PROMOTION_REQUEST);
584        let mut decided: Option<(AutonomyLevel, &JobBinding, String)> = None;
585        for binding in jobs.iter().filter(|b| named.is_none_or(|job| b.job == job)) {
586            let (level, why) = self.level(&binding.job).await;
587            if decided.as_ref().is_none_or(|(held, _, _)| ladder_rank(level) < ladder_rank(*held)) {
588                decided = Some((level, binding, why));
589            }
590        }
591        let Some((level, binding, why)) = decided else {
592            return PolicyDecision::deny(format!(
593                "job {} is not one of {agent}'s jobs that cover {}",
594                named.unwrap_or_default(),
595                request.tool_name
596            ));
597        };
598        let context = |reason: String| {
599            let why = if why.is_empty() { String::new() } else { format!(" ({why})") };
600            format!("{reason}: job {} is at {level:?}{why}", binding.job)
601        };
602        match level_decision(level, spec, request.effect) {
603            LevelDecision::Allow => PolicyDecision::Allow,
604            LevelDecision::Deny(reason) => PolicyDecision::deny(context(reason)),
605            LevelDecision::Hold(reason) => PolicyDecision::require_approval(context(reason)),
606            LevelDecision::WithinBudget => match self.budgets.get(&binding.job) {
607                Some(rules) => rules.decide(request),
608                None => PolicyDecision::require_approval(context("no budget is compiled".into())),
609            },
610        }
611    }
612
613    fn policy_ref(&self) -> Option<String> {
614        Some(format!("adk-harness.website.ladder:{}", self.compiler.site.name))
615    }
616}
617
618/// A job's promotion: its new level and the standing rules the owner's decision created.
619#[derive(Clone, Debug, PartialEq)]
620pub struct Promotion {
621    /// The job's record after the promotion.
622    pub job: JobAutonomy,
623    /// The standing rules granted.
624    pub rules: Vec<StandingRule>,
625}
626
627/// Promotes `job` one rung by the owner's `decision` and grants the standing rules its new
628/// level holds ([`LadderCompiler::rule_tools`]), each created by the owner, revoking those
629/// of the old level the new one does not hold (spec 3.5 §7.11, D-7, A-I13). The kernel's
630/// ladder refuses a decision no person made, and one by a person who is not an owner when it
631/// knows the site's charters; the site itself can never call this to raise its own level.
632///
633/// # Errors
634///
635/// The ladder's refusal, as `Forbidden`; the rule store's error.
636pub async fn promote_job(
637    ladder: &AutonomyLadder,
638    compiler: &LadderCompiler,
639    rules: &dyn StandingRuleStore,
640    job: &str,
641    decision: &OwnerDecision,
642    user: &str,
643) -> adk_core::Result<Promotion> {
644    let record = ladder.promote(compiler.site.id, job, decision).await.map_err(kernel_error)?;
645    let mut granted = Vec::new();
646    for rule in compiler.standing_rules(job, record.level, decision, user) {
647        granted.push(rules.grant(rule).await?);
648    }
649    apply_demotion(compiler, rules, job, record.level).await?;
650    tracing::info!(website.job = job, website.level = ?record.level, decision = %decision.decision_id, "website.job.promoted");
651    Ok(Promotion { job: record, rules: granted })
652}
653
654/// Revokes the standing rules of `job` that its `level` no longer warrants (spec 3.5
655/// §7.11): call it after the kernel's ladder lowers a job, so the harness holds what the job
656/// may no longer do alone. Returns the ids revoked.
657///
658/// # Errors
659///
660/// The rule store's error.
661pub async fn apply_demotion(
662    compiler: &LadderCompiler,
663    rules: &dyn StandingRuleStore,
664    job: &str,
665    level: AutonomyLevel,
666) -> adk_core::Result<Vec<String>> {
667    let keep: BTreeSet<String> = compiler.rule_tools(job, level).into_iter().collect();
668    let Some(binding) = compiler.binding(job) else { return Ok(Vec::new()) };
669    let mut revoked = Vec::new();
670    let candidates: BTreeSet<String> =
671        compiler.rule_tools(job, AutonomyLevel::ActWithinBudget).into_iter().collect();
672    for tool in candidates.difference(&keep) {
673        for kind in [SubjectKind::Human, SubjectKind::Service] {
674            let id = compiler.rule_id(&binding.job, tool, kind);
675            if rules.revoke(&compiler.site.name, &id).await? {
676                revoked.push(id);
677            }
678        }
679    }
680    Ok(revoked)
681}
682
683/// The levels of every job of the compiler's site in `store` (Propose for a job with none).
684///
685/// # Errors
686///
687/// The store's error.
688pub async fn job_levels(
689    compiler: &LadderCompiler,
690    store: &dyn AutonomyStore,
691    site: Uuid,
692) -> adk_core::Result<BTreeMap<String, AutonomyLevel>> {
693    let mut levels = BTreeMap::new();
694    for binding in &compiler.jobs {
695        let level = store
696            .get(site, &binding.job)
697            .await
698            .map_err(kernel_error)?
699            .map_or(AutonomyLevel::Propose, |r| r.level);
700        levels.insert(binding.job.clone(), level);
701    }
702    Ok(levels)
703}