use std::fmt;
use adk_core::Result;
use adk_harness::website::{JobBinding, WebsitePartition};
use adk_kernel::charter::{AutonomyLadder, JobAutonomy, SiteProcessKind, ladder_rank};
use awp_types::{AutonomyLevel, Charter, JobAuthority, JobLimits};
use serde::{Deserialize, Serialize};
use serde_json::json;
use crate::team::{AgentRole, SiteTeam};
use AgentRole::{AgentDesk, Concierge, Finance, Growth, Guardian, Inbox, Revenue, Steward};
use AutonomyLevel::{ActReversibleOnly, ActWithApproval, ActWithinBudget, Propose};
use JobEffect::{
CapabilityEffects, Financial, OwnerChannels, PublishPublic, Read, SendExternal, Signals,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum JobArea {
RunAndProtect,
BeFound,
Serve,
Grow,
Money,
Account,
}
impl JobArea {
pub fn as_str(self) -> &'static str {
match self {
Self::RunAndProtect => "run-and-protect",
Self::BeFound => "be-found",
Self::Serve => "serve",
Self::Grow => "grow",
Self::Money => "money",
Self::Account => "account",
}
}
}
impl fmt::Display for JobArea {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum JobEffect {
Read,
PublishPublic,
Financial,
SendExternal,
OwnerChannels,
Signals,
CapabilityEffects,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "policy", content = "level", rename_all = "snake_case")]
pub enum StartsAt {
Manifest,
Level(AutonomyLevel),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum JobNeed {
Nothing,
Advertising,
Sales,
Wallet,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct JobSpec {
pub id: &'static str,
pub area: JobArea,
pub title: &'static str,
pub agents: &'static [AgentRole],
pub starts_at: StartsAt,
pub note: &'static str,
pub effects: &'static [JobEffect],
pub tools: &'static [&'static str],
pub needs: JobNeed,
pub process: Option<SiteProcessKind>,
pub playbook: &'static str,
}
impl JobSpec {
pub fn ladder_agent(&self, team: &SiteTeam) -> Option<AgentRole> {
match self.starts_at {
StartsAt::Manifest => None,
StartsAt::Level(_) => {
self.agents.iter().copied().find(|role| {
role.partition() == WebsitePartition::BackOffice && team.runs(*role)
})
}
}
}
pub fn first_week_level(&self) -> Option<AutonomyLevel> {
let StartsAt::Level(level) = self.starts_at else { return None };
Some(match (self.id, level) {
(ONBOARDING, _) => AutonomyLevel::ActWithApproval,
(_, AutonomyLevel::Observe) => AutonomyLevel::Observe,
_ => AutonomyLevel::Propose,
})
}
}
pub const ONBOARDING: &str = "onboarding";
pub const JOBS: &[JobSpec] = &[
JobSpec {
id: ONBOARDING,
area: JobArea::Account,
title: "Onboarding and launch: build release 1 while the owner talks",
agents: &[Steward],
starts_at: StartsAt::Level(ActWithApproval),
note: "Production publication at launch is held in every mode (A-I21)",
effects: &[PublishPublic],
tools: &[
"content_*",
"translation_draft",
"media_intake",
"release_preview",
"site_publish",
"site_discover",
"interview_record",
"launch_gate_run",
"awp_verify",
"host_fetch",
],
needs: JobNeed::Nothing,
process: None,
playbook: "onboarding",
},
JobSpec {
id: "protect",
area: JobArea::RunAndProtect,
title: "Static content, signed releases, drift rollback, site watch, abuse throttling",
agents: &[Guardian],
starts_at: StartsAt::Level(ActReversibleOnly),
note: "Rollback and read-only are the only incident acts (A-I11)",
effects: &[PublishPublic],
tools: &["site_rollback", "edge_read_only", "host_fetch", "awp_verify"],
needs: JobNeed::Nothing,
process: Some(SiteProcessKind::Probe),
playbook: "protect",
},
JobSpec {
id: "alarms",
area: JobArea::RunAndProtect,
title: "Alarms by urgency and channel",
agents: &[Guardian],
starts_at: StartsAt::Level(ActWithinBudget),
note: "Act",
effects: &[OwnerChannels],
tools: &[],
needs: JobNeed::Nothing,
process: None,
playbook: "alarms",
},
JobSpec {
id: "freshness",
area: JobArea::RunAndProtect,
title: "Freshness: stale facts, broken links, outdated pages",
agents: &[Growth],
starts_at: StartsAt::Level(ActWithinBudget),
note: "Within budget for edits; Propose for new pages",
effects: &[PublishPublic],
tools: &[
"content_draft",
"content_edit",
"content_correct",
"content_revert",
"content_schedule",
"release_preview",
"site_publish",
],
needs: JobNeed::Nothing,
process: Some(SiteProcessKind::Content),
playbook: "freshness",
},
JobSpec {
id: "hosting",
area: JobArea::RunAndProtect,
title: "Hosting, domains, certificates, backups",
agents: &[Guardian, Finance],
starts_at: StartsAt::Level(Propose),
note: "Propose; renewals within budget",
effects: &[PublishPublic, Financial],
tools: &["launch_gate_run"],
needs: JobNeed::Nothing,
process: Some(SiteProcessKind::Watch),
playbook: "hosting",
},
JobSpec {
id: "seo",
area: JobArea::BeFound,
title: "SEO",
agents: &[Growth],
starts_at: StartsAt::Level(ActWithinBudget),
note: "Within budget",
effects: &[PublishPublic],
tools: &["content_edit", "release_preview", "site_publish"],
needs: JobNeed::Nothing,
process: None,
playbook: "seo",
},
JobSpec {
id: "aeo",
area: JobArea::BeFound,
title: "AEO",
agents: &[Growth],
starts_at: StartsAt::Level(ActWithinBudget),
note: "Within budget; tracking at Observe",
effects: &[PublishPublic, Read],
tools: &["content_draft", "content_edit", "release_preview", "site_publish"],
needs: JobNeed::Nothing,
process: None,
playbook: "aeo",
},
JobSpec {
id: "agent-search",
area: JobArea::BeFound,
title: "Agent search",
agents: &[Growth],
starts_at: StartsAt::Level(ActWithinBudget),
note: "Act",
effects: &[PublishPublic],
tools: &["release_preview", "site_publish", "awp_verify"],
needs: JobNeed::Nothing,
process: None,
playbook: "agent-search",
},
JobSpec {
id: "multilingual",
area: JobArea::Serve,
title: "Multilingual pages and conversation",
agents: &[Concierge, Growth],
starts_at: StartsAt::Level(ActWithinBudget),
note: "Act; a new language at Propose",
effects: &[PublishPublic],
tools: &["translation_draft", "release_preview", "site_publish"],
needs: JobNeed::Nothing,
process: None,
playbook: "multilingual",
},
JobSpec {
id: "presentations",
area: JobArea::Serve,
title: "Presentations by role and need",
agents: &[Concierge],
starts_at: StartsAt::Manifest,
note: "Act",
effects: &[],
tools: &[],
needs: JobNeed::Nothing,
process: None,
playbook: "presentations",
},
JobSpec {
id: "agent-front-door",
area: JobArea::Serve,
title: "Agent front door",
agents: &[AgentDesk],
starts_at: StartsAt::Manifest,
note: "Act within policy",
effects: &[CapabilityEffects],
tools: &[],
needs: JobNeed::Nothing,
process: None,
playbook: "agent-front-door",
},
JobSpec {
id: "email",
area: JobArea::Serve,
title: "The site's email",
agents: &[Inbox, Revenue],
starts_at: StartsAt::Level(ActWithinBudget),
note: "Within playbook; Propose otherwise",
effects: &[SendExternal],
tools: &[],
needs: JobNeed::Nothing,
process: None,
playbook: "email",
},
JobSpec {
id: "social",
area: JobArea::Serve,
title: "Social engagement",
agents: &[Inbox, Growth],
starts_at: StartsAt::Level(Propose),
note: "Propose, then playbook",
effects: &[SendExternal, PublishPublic],
tools: &["content_draft", "content_edit", "release_preview", "site_publish", "social_post"],
needs: JobNeed::Nothing,
process: Some(SiteProcessKind::Reviews),
playbook: "review-replies",
},
JobSpec {
id: "advertising",
area: JobArea::Serve,
title: "Advertising",
agents: &[Growth, Finance],
starts_at: StartsAt::Level(Propose),
note: "Propose to launch; within budget to tune",
effects: &[Financial, PublishPublic],
tools: &[],
needs: JobNeed::Advertising,
process: None,
playbook: "advertising",
},
JobSpec {
id: "capture",
area: JobArea::Grow,
title: "Lead, sign-up or request capture from every channel",
agents: &[Concierge, Inbox, AgentDesk],
starts_at: StartsAt::Manifest,
note: "Act",
effects: &[Signals],
tools: &[],
needs: JobNeed::Nothing,
process: None,
playbook: "capture",
},
JobSpec {
id: "nurture",
area: JobArea::Grow,
title: "Qualify and nurture with consent",
agents: &[Revenue],
starts_at: StartsAt::Level(ActWithinBudget),
note: "Within playbook",
effects: &[SendExternal],
tools: &["email_send_sequence_step"],
needs: JobNeed::Nothing,
process: Some(SiteProcessKind::Outreach),
playbook: "nurture",
},
JobSpec {
id: "handoff",
area: JobArea::Grow,
title: "Warm handoff with context",
agents: &[Revenue],
starts_at: StartsAt::Level(ActWithinBudget),
note: "Act",
effects: &[OwnerChannels],
tools: &["lead_handoff"],
needs: JobNeed::Nothing,
process: None,
playbook: "handoff",
},
JobSpec {
id: "sell",
area: JobArea::Grow,
title: "Sell: quotes, checkout, bookings, receipts",
agents: &[Revenue],
starts_at: StartsAt::Level(ActWithinBudget),
note: "Within payment policy",
effects: &[Financial],
tools: &[],
needs: JobNeed::Sales,
process: None,
playbook: "sell",
},
JobSpec {
id: "experiments",
area: JobArea::Grow,
title: "Experiments",
agents: &[Growth],
starts_at: StartsAt::Level(ActWithinBudget),
note: "Within budget",
effects: &[PublishPublic],
tools: &[
"content_draft",
"release_preview",
"site_publish",
"experiment_start",
"experiment_report",
],
needs: JobNeed::Nothing,
process: None,
playbook: "experiments",
},
JobSpec {
id: "playbook-learning",
area: JobArea::Grow,
title: "Playbook learning",
agents: &[Steward],
starts_at: StartsAt::Level(Propose),
note: "Propose",
effects: &[],
tools: &[],
needs: JobNeed::Nothing,
process: None,
playbook: "playbook-learning",
},
JobSpec {
id: "running-costs",
area: JobArea::Money,
title: "Pay running costs under mandates",
agents: &[Finance],
starts_at: StartsAt::Level(ActWithinBudget),
note: "Within budget",
effects: &[Financial],
tools: &["wallet_pay"],
needs: JobNeed::Wallet,
process: None,
playbook: "running-costs",
},
JobSpec {
id: "cost-and-return",
area: JobArea::Money,
title: "Cost and return; budget moves within caps",
agents: &[Finance],
starts_at: StartsAt::Level(ActWithinBudget),
note: "Within budget",
effects: &[],
tools: &["wallet_status"],
needs: JobNeed::Wallet,
process: None,
playbook: "cost-and-return",
},
JobSpec {
id: "goals",
area: JobArea::Account,
title: "Goals, strategy, KPIs",
agents: &[Steward],
starts_at: StartsAt::Level(Propose),
note: "Propose",
effects: &[],
tools: &["charter_draft", "charter_commit_request"],
needs: JobNeed::Nothing,
process: None,
playbook: "goals",
},
JobSpec {
id: "weekly-review",
area: JobArea::Account,
title: "Weekly review and reports",
agents: &[Steward, Finance],
starts_at: StartsAt::Level(ActWithinBudget),
note: "Act",
effects: &[OwnerChannels],
tools: &["job_promotion_request"],
needs: JobNeed::Nothing,
process: Some(SiteProcessKind::Digest),
playbook: "weekly-review",
},
JobSpec {
id: "owner-questions",
area: JobArea::Account,
title: "Questions for the owner",
agents: &[Steward],
starts_at: StartsAt::Level(ActWithinBudget),
note: "Act",
effects: &[OwnerChannels],
tools: &[],
needs: JobNeed::Nothing,
process: Some(SiteProcessKind::Support),
playbook: "owner-questions",
},
];
pub fn job(id: &str) -> Option<&'static JobSpec> {
JOBS.iter().find(|job| job.id == id)
}
pub fn bindings(team: &SiteTeam, jobs: &[&JobSpec]) -> Vec<JobBinding> {
jobs.iter()
.filter_map(|job| {
let agent = job.ladder_agent(team)?;
Some(
JobBinding::new(job.id, agent.as_str(), job.tools.iter().copied())
.in_area(job.area.as_str()),
)
})
.collect()
}
pub fn first_week_authority(
team: &SiteTeam,
jobs: &[&JobSpec],
actions_per_day: u32,
) -> Vec<JobAuthority> {
jobs.iter()
.filter(|job| job.ladder_agent(team).is_some())
.filter_map(|job| {
let level = job.first_week_level()?;
let limits = match job.starts_at {
StartsAt::Level(ActWithinBudget) => {
JobLimits { spend_cap: None, actions_per_day: Some(actions_per_day) }
}
_ => JobLimits::default(),
};
Some(JobAuthority { job: job.id.to_string(), level, limits })
})
.collect()
}
pub fn starting_levels(charter: &Charter) -> Vec<(String, AutonomyLevel)> {
charter
.authority
.iter()
.filter_map(|authority| {
let StartsAt::Level(start) = job(&authority.job)?.starts_at else { return None };
(ladder_rank(start) > ladder_rank(authority.level))
.then(|| (authority.job.clone(), start))
})
.collect()
}
pub async fn register(ladder: &AutonomyLadder, charter: &Charter) -> Result<Vec<JobAutonomy>> {
let error = |e: adk_kernel::KernelError| adk_core::AdkError::config(e.to_string());
for authority in &charter.authority {
let area = job(&authority.job).map(|job| job.area.as_str());
ladder
.register(charter.site_id, &authority.job, authority.level, area)
.await
.map_err(error)?;
}
ladder.sync(charter).await.map_err(error)
}
pub async fn register_onboarding(ladder: &AutonomyLadder, site: uuid::Uuid) -> Result<JobAutonomy> {
ladder
.register(site, ONBOARDING, AutonomyLevel::ActWithApproval, Some(JobArea::Account.as_str()))
.await
.map_err(|e| adk_core::AdkError::config(e.to_string()))
}
#[derive(Debug, Clone, PartialEq)]
pub struct SiteProcess {
pub kind: SiteProcessKind,
pub job: &'static str,
pub target: String,
pub input: serde_json::Value,
}
pub const PROBE_WORKFLOW: &str = "website.guardian.probe";
pub const DIGEST_WORKFLOW: &str = "website.steward.digest";
pub const WATCH_WORKFLOW: &str = "website.guardian.watch";
pub fn processes(team: &SiteTeam, jobs: &[&JobSpec]) -> Vec<SiteProcess> {
jobs.iter()
.filter_map(|job| {
let kind = job.process?;
let agent = job.ladder_agent(team)?;
let target = match kind {
SiteProcessKind::Probe => PROBE_WORKFLOW.to_string(),
SiteProcessKind::Digest => DIGEST_WORKFLOW.to_string(),
SiteProcessKind::Watch => WATCH_WORKFLOW.to_string(),
_ => agent.as_str().to_string(),
};
let input = json!({
"site": team.site().id,
"job": job.id,
"playbook": job.playbook,
"text": format!("Run the {} playbook for job {}.", job.playbook, job.id),
});
Some(SiteProcess { kind, job: job.id, target, input })
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ids_are_unique_and_every_job_has_its_playbook() {
let mut ids: Vec<&str> = JOBS.iter().map(|j| j.id).collect();
ids.sort_unstable();
ids.dedup();
assert_eq!(ids.len(), JOBS.len());
for job in JOBS {
assert!(crate::playbooks::playbook(job.playbook).is_some(), "{}", job.id);
}
}
#[test]
fn every_acting_job_binds_tools_its_agent_holds() {
let unbound: Vec<&str> = JOBS
.iter()
.filter(|job| matches!(job.starts_at, StartsAt::Level(_)) && job.tools.is_empty())
.map(|job| job.id)
.collect();
assert_eq!(
unbound,
["alarms", "email", "advertising", "sell", "playbook-learning", "owner-questions"]
);
for job in JOBS.iter().filter(|job| matches!(job.starts_at, StartsAt::Level(_))) {
let agent = job
.agents
.iter()
.find(|role| role.partition() == WebsitePartition::BackOffice)
.expect("a back-office job has a back-office agent");
let held = JobBinding::new(job.id, agent.as_str(), agent.tools().iter().copied());
for tool in job.tools {
assert!(held.covers(tool), "{} binds {tool}, which {agent} does not hold", job.id);
}
}
}
#[test]
fn first_week_levels_are_observe_or_propose_but_onboarding() {
for job in JOBS {
match job.first_week_level() {
None => assert_eq!(job.starts_at, StartsAt::Manifest),
Some(AutonomyLevel::ActWithApproval) => assert_eq!(job.id, ONBOARDING),
Some(level) => {
assert!(matches!(level, AutonomyLevel::Observe | AutonomyLevel::Propose))
}
}
}
}
}