1use 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#[derive(Clone, Debug, PartialEq, Eq)]
40pub enum LevelDecision {
41 Allow,
43 Deny(String),
45 Hold(String),
47 WithinBudget,
49}
50
51pub 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 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
104pub 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#[derive(Clone, Debug, PartialEq)]
140pub struct JobBinding {
141 pub job: String,
143 pub agent: String,
145 pub tools: Vec<String>,
147 pub area: Option<String>,
149 pub predicates: Vec<(String, ArgPredicate)>,
151 pub run_budget: Option<RunBudget>,
153 pub origins: BTreeMap<String, String>,
155}
156
157impl JobBinding {
158 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 #[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 #[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 #[must_use]
191 pub fn with_run_budget(mut self, budget: RunBudget) -> Self {
192 self.run_budget = Some(budget);
193 self
194 }
195
196 #[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 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#[derive(Clone, Debug)]
225pub struct LadderCompiler {
226 site: SiteRef,
227 jobs: Vec<JobBinding>,
228}
229
230impl LadderCompiler {
231 pub fn new(site: SiteRef) -> Self {
233 Self { site, jobs: Vec::new() }
234 }
235
236 #[must_use]
238 pub fn job(mut self, binding: JobBinding) -> Self {
239 self.jobs.push(binding);
240 self
241 }
242
243 #[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 #[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 pub fn site(&self) -> &SiteRef {
308 &self.site
309 }
310
311 pub fn jobs(&self) -> &[JobBinding] {
313 &self.jobs
314 }
315
316 pub fn binding(&self, job: &str) -> Option<&JobBinding> {
318 self.jobs.iter().find(|binding| binding.job == job)
319 }
320
321 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 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 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 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 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 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 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
502struct 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 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#[derive(Clone, Debug, PartialEq)]
620pub struct Promotion {
621 pub job: JobAutonomy,
623 pub rules: Vec<StandingRule>,
625}
626
627pub 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
654pub 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
683pub 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}