Skip to main content

adk_website/
learning.rs

1//! Learning (spec 3.5 §7.15, §7.20 "Playbook learning", §7.23, A-I13): the week's outcomes
2//! become proposals to revise playbooks, which land only as the owner's decisions.
3//!
4//! The `playbook-learning` job runs with the weekly review ([`LEARNING_WORKFLOW`] on
5//! [`LEARNING_CRON`]): [`PlaybookLearning::learn`] composes the review, reads the
6//! experiments, and drafts one proposal per outcome that carries enough evidence. Each
7//! proposal names the playbook, the change as a diff of its text, the evidence with links to
8//! the reviews, and the expected effect.
9//!
10//! | Outcome | Enough evidence | Playbook | The change |
11//! |---|---|---|---|
12//! | An experiment | Stopped by the sequential test's decision with its fixed error budget (§7.12): the variant adopted, or the control kept because the variant is worse, with the primary metric ready | The playbook of the experiment's job | "Prefer" or "Avoid" what it tested |
13//! | A KPI | A baseline and the owner's target (A-I14), and the means of [`KPI_MISS_WEEKS`] weekly reviews in a row short of the target in its direction | The playbook [`kpi_playbook`] names for its metric | Give the KPI priority |
14//!
15//! An experiment stopped by a guardrail or at its sample limit, a running one, and a KPI in
16//! its measure-only period or missing its target for one week propose nothing. An experiment
17//! proposes once; a KPI at most once in [`KPI_PROPOSAL_INTERVAL_DAYS`].
18//!
19//! | The learning job's level | A proposal |
20//! |---|---|
21//! | Observe | Reported only: no card (§7.11, "output goes to reports") |
22//! | Propose and every level above | The owner's decision card ([`PLAYBOOK_REVISION`]): accept, edit or decline |
23//!
24//! A revision is applied only by the owner's decision, at every level (§7.15, A-I13): an
25//! accepted or edited revision becomes the playbook's next version in [`PlaybookVersions`],
26//! written into the workspace of every agent that runs the playbook; a declined or expired
27//! one changes nothing. Each decision counts on the ladder for the learning job as an
28//! approval, an edit or a rejection (§7.11).
29
30use std::path::{Path, PathBuf};
31use std::sync::Arc;
32use std::time::Duration;
33
34use adk_core::schedule::MissedFirePolicy;
35use adk_core::{
36    AdkError, ApprovalAction, ApprovalPolicy, ApprovalRequest, ApprovalRisk, ApprovalScope,
37    ApprovalService, ApprovalState, ApproverSelector, Clock, NewRun, Result, SystemClock,
38    ToolConfirmationRequest,
39};
40use adk_eval::experiments::{Decision, MetricKind, StopReason};
41use adk_harness::website::SiteRef;
42use adk_kernel::QueueClass;
43use adk_kernel::charter::{AutonomyLadder, CharterStore, DecisionOutcome, JobDecision, KpiPhase};
44use adk_kernel::wake::{Trigger, Wake};
45use awp_types::{AutonomyLevel, Direction, Kpi};
46use chrono::{DateTime, Datelike, NaiveDate, Utc};
47use serde::{Deserialize, Serialize};
48use serde_json::{Value, json};
49use tokio::sync::Mutex;
50use tokio::task::JoinHandle;
51use uuid::Uuid;
52
53use crate::experiments::{ExperimentRecord, ExperimentRunner, ExperimentStatus};
54use crate::review::{KpiLine, ReviewComposer, ReviewInputs, WeeklyReview};
55use crate::team::SiteTeam;
56
57/// The job that learns (spec 3.5 §7.20).
58pub const LEARNING_JOB: &str = "playbook-learning";
59/// The workflow the weekly learning run executes in the site's kernel.
60pub const LEARNING_WORKFLOW: &str = "website.steward.learning";
61/// When the learning run fires: Mondays at 07:30 UTC, after the weekly review at 07:00.
62pub const LEARNING_CRON: &str = "0 30 7 * * MON";
63/// The tool a proposal's decision card names.
64pub const PLAYBOOK_REVISION: &str = "website_playbook_revision";
65/// The web home's weekly review page, which the evidence links to (`adk-surface`'s
66/// `website` views).
67pub const REVIEW_PATH: &str = "/surface/website/review";
68/// The weekly reviews in a row a KPI must miss its target in before it proposes.
69pub const KPI_MISS_WEEKS: usize = 2;
70/// The days a KPI waits before it proposes again.
71pub const KPI_PROPOSAL_INTERVAL_DAYS: i64 = 28;
72/// The heading learned lines are kept under.
73const LEARNED: &str = "## Learned";
74
75fn config(error: impl std::fmt::Display) -> AdkError {
76    AdkError::config(error.to_string())
77}
78
79/// The Monday of `day`'s week.
80fn monday(day: NaiveDate) -> NaiveDate {
81    day - chrono::Duration::days(i64::from(day.weekday().num_days_from_monday()))
82}
83
84/// Whether one of `id`'s agents runs on the site.
85fn runs(id: &str, team: &SiteTeam) -> bool {
86    crate::playbooks::playbook(id).is_some_and(|p| p.agents.iter().any(|role| team.runs(*role)))
87}
88
89/// The playbook a KPI's metric is moved by: the job its metric's first segment names, else
90/// the Steward's `goals`, and `goals` when no agent of the site runs the playbook.
91///
92/// | Metric | Playbook |
93/// |---|---|
94/// | `leads.*`, `events.*` | `capture` |
95/// | `newsletter.*`, `subscriptions.*`, `donations.*`, `volunteers.*` | `nurture` |
96/// | `orders.*`, `payments.*`, `tickets.*`, `bookings.*`, `services.*` | `sell` |
97/// | `content.*`, `catalog.*`, `notices.*`, `corrections.*` | `freshness` |
98/// | `visits.*`, `search.*` | `seo` |
99/// | `pages.*` | `aeo` |
100/// | `agents.*` | `agent-search` |
101/// | `conversations.*`, `a11y.*` | `presentations` |
102/// | `reviews.*` | `review-replies` |
103/// | `email.*` | `email` |
104/// | `spend.*`, `profit`, `revenue` | `cost-and-return` |
105///
106/// # Example
107///
108/// ```rust
109/// use adk_harness::website::SiteRef;
110/// use adk_website::kinds::template;
111/// use adk_website::learning::kpi_playbook;
112/// use adk_website::team::SiteTeam;
113/// use awp_types::SiteKind;
114///
115/// let site = SiteRef::new(uuid::Uuid::nil(), "bakery", "https://bakery.example");
116/// let business = SiteTeam::new(site.clone(), &template(SiteKind::Business));
117/// assert_eq!(kpi_playbook("newsletter.signups", &business), "nurture");
118/// let personal = SiteTeam::new(site, &template(SiteKind::Personal));
119/// assert_eq!(kpi_playbook("orders.count", &personal), "goals", "no Revenue on a personal site");
120/// ```
121pub fn kpi_playbook(metric: &str, team: &SiteTeam) -> &'static str {
122    let id = match metric.split('.').next().unwrap_or_default() {
123        "leads" | "events" => "capture",
124        "newsletter" | "subscriptions" | "donations" | "volunteers" => "nurture",
125        "orders" | "payments" | "tickets" | "bookings" | "services" => "sell",
126        "content" | "catalog" | "notices" | "corrections" => "freshness",
127        "visits" | "search" => "seo",
128        "pages" => "aeo",
129        "agents" => "agent-search",
130        "conversations" | "a11y" => "presentations",
131        "reviews" => "review-replies",
132        "email" => "email",
133        "spend" | "profit" | "revenue" => "cost-and-return",
134        _ => "goals",
135    };
136    if runs(id, team) { id } else { "goals" }
137}
138
139/// The playbook of `job`, else `goals` when the job has none the site runs.
140fn job_playbook(job: &str, team: &SiteTeam) -> &'static str {
141    crate::jobs::JOBS
142        .iter()
143        .find(|spec| spec.id == job)
144        .map(|spec| spec.playbook)
145        .filter(|id| runs(id, team))
146        .unwrap_or("goals")
147}
148
149/// `text` with `line` under its `## Learned` heading, which is added at the end when the
150/// playbook has none.
151///
152/// # Example
153///
154/// ```rust
155/// use adk_website::learning::revise;
156///
157/// let once = revise("# SEO\n\nWrite titles.\n", "- Prefer short titles.");
158/// assert_eq!(once, "# SEO\n\nWrite titles.\n\n## Learned\n\n- Prefer short titles.\n");
159/// let twice = revise(&once, "- Avoid questions in titles.");
160/// assert!(twice.ends_with("- Prefer short titles.\n- Avoid questions in titles.\n"));
161/// ```
162pub fn revise(text: &str, line: &str) -> String {
163    let body = text.trim_end();
164    match body.find(&format!("\n{LEARNED}\n")) {
165        Some(_) => format!("{body}\n{line}\n"),
166        None => format!("{body}\n\n{LEARNED}\n\n{line}\n"),
167    }
168}
169
170/// The unified diff of `before` to `after` for playbook `id`.
171fn diff(id: &str, before: &str, after: &str) -> String {
172    similar::TextDiff::from_lines(before, after)
173        .unified_diff()
174        .context_radius(3)
175        .header(&format!("a/{id}.md"), &format!("b/{id}.md"))
176        .to_string()
177}
178
179/// What kind of outcome a proposal learns from.
180#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
181#[serde(rename_all = "snake_case")]
182pub enum OutcomeKind {
183    /// An experiment's decision (spec 3.5 §7.12).
184    Experiment,
185    /// A KPI against the owner's target (spec 3.5 §7.11).
186    Kpi,
187}
188
189/// The evidence behind a proposal, with a link to the report that holds it.
190#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
191#[serde(rename_all = "camelCase")]
192pub struct Evidence {
193    /// The kind of outcome.
194    pub kind: OutcomeKind,
195    /// The outcome in one line.
196    pub summary: String,
197    /// The weekly review that reports it, on the web home.
198    pub link: String,
199}
200
201/// Where a proposal stands.
202#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
203#[serde(rename_all = "snake_case")]
204pub enum ProposalState {
205    /// Reported only: the learning job is at Observe.
206    Reported,
207    /// Waiting for the owner's decision card.
208    Proposed,
209    /// Accepted, as proposed or edited: the playbook's next version.
210    Accepted,
211    /// Declined, or the card expired: the playbook is unchanged.
212    Declined,
213}
214
215/// A proposal to revise one playbook (spec 3.5 §7.15).
216#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
217#[serde(rename_all = "camelCase")]
218pub struct PlaybookProposal {
219    /// The proposal's id, also its card's.
220    pub id: String,
221    /// The site.
222    pub site: Uuid,
223    /// The outcome it learns from: `experiment:{id}` or `kpi:{id}`.
224    pub key: String,
225    /// The playbook.
226    pub playbook: String,
227    /// The version it revises.
228    pub base_version: u32,
229    /// The line it adds under `## Learned`.
230    pub addition: String,
231    /// The playbook's text after the change.
232    pub text: String,
233    /// The change, as a unified diff of the playbook's text.
234    pub diff: String,
235    /// The evidence.
236    pub evidence: Vec<Evidence>,
237    /// What the change is expected to do.
238    pub expected_effect: String,
239    /// Where it stands.
240    pub state: ProposalState,
241    /// The owner's decision card, when it has one.
242    #[serde(default, skip_serializing_if = "Option::is_none")]
243    pub card: Option<String>,
244    /// The version accepting it made.
245    #[serde(default, skip_serializing_if = "Option::is_none")]
246    pub version: Option<u32>,
247    /// Whether the owner edited it before accepting.
248    #[serde(default)]
249    pub edited: bool,
250    /// Who decided.
251    #[serde(default, skip_serializing_if = "Option::is_none")]
252    pub decided_by: Option<String>,
253    /// When it was drafted.
254    pub created_at: DateTime<Utc>,
255    /// When the owner decided.
256    #[serde(default, skip_serializing_if = "Option::is_none")]
257    pub decided_at: Option<DateTime<Utc>>,
258}
259
260/// One version of a playbook.
261#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
262#[serde(rename_all = "camelCase")]
263pub struct PlaybookVersion {
264    /// The playbook.
265    pub playbook: String,
266    /// Its version: 1 is the text installed in the agents' workspaces.
267    pub version: u32,
268    /// The text.
269    pub text: String,
270    /// The proposal that made it.
271    #[serde(default, skip_serializing_if = "Option::is_none")]
272    pub proposal: Option<String>,
273    /// The person who accepted it.
274    #[serde(default, skip_serializing_if = "Option::is_none")]
275    pub accepted_by: Option<String>,
276    /// When it was accepted.
277    #[serde(default, skip_serializing_if = "Option::is_none")]
278    pub at: Option<DateTime<Utc>>,
279}
280
281/// A site's playbooks with their versions (spec 3.5 §7.15): version 1 is the text in the
282/// agents' workspaces (a developer's playbook, else the built-in one); each accepted revision
283/// is the next, kept in `{dir}/{playbook}.json` and written to
284/// `{workspaces}/{agent}/.skills/{playbook}.md` for every agent that runs it.
285///
286/// # Example
287///
288/// ```rust
289/// use adk_website::learning::PlaybookVersions;
290///
291/// # #[tokio::main(flavor = "current_thread")]
292/// # async fn main() -> adk_core::Result<()> {
293/// let dir = tempfile::tempdir().unwrap();
294/// let versions = PlaybookVersions::new(dir.path().join("playbooks"), dir.path().join("agents"));
295/// let seo = versions.current("seo").await?;
296/// assert_eq!(seo.version, 1);
297/// let next = versions.accept("seo", "# SEO\n", "p-1", "amina", chrono::Utc::now()).await?;
298/// assert_eq!(next.version, 2);
299/// assert_eq!(std::fs::read_to_string(dir.path().join("agents/growth/.skills/seo.md")).unwrap(), "# SEO\n");
300/// # Ok(())
301/// # }
302/// ```
303#[derive(Debug, Clone)]
304pub struct PlaybookVersions {
305    dir: PathBuf,
306    workspaces: PathBuf,
307}
308
309impl PlaybookVersions {
310    /// Versions under `dir`, for the agents' workspaces under `workspaces`.
311    pub fn new(dir: impl Into<PathBuf>, workspaces: impl Into<PathBuf>) -> Self {
312        Self { dir: dir.into(), workspaces: workspaces.into() }
313    }
314
315    fn known(id: &str) -> Result<&'static crate::playbooks::Playbook> {
316        crate::playbooks::playbook(id)
317            .ok_or_else(|| config(format!("`{id}` is not one of the site's playbooks")))
318    }
319
320    /// The accepted revisions of `id`, oldest first; none until one is accepted.
321    ///
322    /// # Errors
323    ///
324    /// An unknown playbook, or a file that does not read.
325    pub async fn history(&self, id: &str) -> Result<Vec<PlaybookVersion>> {
326        Self::known(id)?;
327        let path = self.dir.join(format!("{id}.json"));
328        match tokio::fs::read(&path).await {
329            Ok(bytes) => serde_json::from_slice(&bytes).map_err(config),
330            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
331            Err(error) => Err(config(format!("{}: {error}", path.display()))),
332        }
333    }
334
335    /// The version of `id` in force.
336    ///
337    /// # Errors
338    ///
339    /// As [`history`](Self::history).
340    pub async fn current(&self, id: &str) -> Result<PlaybookVersion> {
341        let playbook = Self::known(id)?;
342        if let Some(latest) = self.history(id).await?.pop() {
343            return Ok(latest);
344        }
345        let mut text = playbook.text.to_string();
346        for role in playbook.agents {
347            let installed =
348                self.workspaces.join(role.as_str()).join(".skills").join(format!("{id}.md"));
349            if let Ok(found) = tokio::fs::read_to_string(&installed).await {
350                text = found;
351                break;
352            }
353        }
354        Ok(PlaybookVersion {
355            playbook: id.to_string(),
356            version: 1,
357            text,
358            proposal: None,
359            accepted_by: None,
360            at: None,
361        })
362    }
363
364    /// Makes `text` the next version of `id`, accepted by `by` from `proposal`, and writes it
365    /// into the workspace of every agent that runs it.
366    ///
367    /// # Errors
368    ///
369    /// As [`history`](Self::history), or a file that does not write.
370    pub async fn accept(
371        &self,
372        id: &str,
373        text: &str,
374        proposal: &str,
375        by: &str,
376        at: DateTime<Utc>,
377    ) -> Result<PlaybookVersion> {
378        let playbook = Self::known(id)?;
379        let current = self.current(id).await?;
380        let mut history = self.history(id).await?;
381        let version = PlaybookVersion {
382            playbook: id.to_string(),
383            version: current.version + 1,
384            text: text.to_string(),
385            proposal: Some(proposal.to_string()),
386            accepted_by: Some(by.to_string()),
387            at: Some(at),
388        };
389        history.push(version.clone());
390        write_json(&self.dir.join(format!("{id}.json")), &history).await?;
391        for role in playbook.agents {
392            let skills = self.workspaces.join(role.as_str()).join(".skills");
393            write_atomic(&skills.join(format!("{id}.md")), text.as_bytes()).await?;
394        }
395        Ok(version)
396    }
397}
398
399async fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> {
400    if let Some(parent) = path.parent() {
401        tokio::fs::create_dir_all(parent).await.map_err(config)?;
402    }
403    let temporary = path.with_extension("tmp");
404    tokio::fs::write(&temporary, bytes).await.map_err(config)?;
405    tokio::fs::rename(&temporary, path).await.map_err(config)
406}
407
408async fn write_json(path: &Path, value: &impl Serialize) -> Result<()> {
409    write_atomic(path, &serde_json::to_vec_pretty(value).map_err(config)?).await
410}
411
412/// What one outcome teaches, before it is a proposal.
413struct Lesson {
414    key: String,
415    once: bool,
416    week: NaiveDate,
417    playbook: &'static str,
418    line: String,
419    evidence: Evidence,
420    expected_effect: String,
421}
422
423/// The lesson of a decided experiment; `None` for one that is running, stopped by a
424/// guardrail or at its sample limit, or decided before its primary metric was ready.
425fn experiment_lesson(record: &ExperimentRecord, team: &SiteTeam) -> Option<Lesson> {
426    let ExperimentStatus::Stopped { decision, at, .. } = &record.status else { return None };
427    let report = record.latest.as_ref().filter(|report| report.primary.ready)?;
428    let adopted = match decision {
429        Decision::AdoptVariant => true,
430        Decision::KeepControl { reason: StopReason::VariantWorse } => false,
431        _ => return None,
432    };
433    let plan = &record.plan;
434    let primary = &report.primary;
435    let value = |v: f64| match primary.kind {
436        MetricKind::Proportion => format!("{:.1}%", v * 100.0),
437        _ => format!("{v:.2}"),
438    };
439    let (control, variant) = (value(primary.effect.control), value(primary.effect.variant));
440    let lift = primary
441        .effect
442        .relative_lift
443        .map(|lift| format!(" ({:+.1}% relative)", lift * 100.0))
444        .unwrap_or_default();
445    let what = if plan.hypothesis.is_empty() {
446        format!("the variant of {}", plan.page)
447    } else {
448        plan.hypothesis.trim_end_matches('.').to_string()
449    };
450    let (verb, moved, expected_effect) = if adopted {
451        (
452            "Prefer",
453            "improved",
454            format!(
455                "Pages this playbook drafts move {} from about {control} towards {variant}, as \
456                 experiment `{}` measured",
457                primary.metric, plan.id
458            ),
459        )
460    } else {
461        (
462            "Avoid",
463            "worsened",
464            format!(
465                "Pages this playbook drafts keep {} near {control} instead of the {variant} the \
466                 variant of experiment `{}` reached",
467                primary.metric, plan.id
468            ),
469        )
470    };
471    let line = format!(
472        "- {verb} what experiment `{}` tested on {}: {what}. It {moved} {} from {control} to \
473         {variant}{lift}.",
474        plan.id, plan.page, primary.metric
475    );
476    let week = monday(at.date_naive());
477    Some(Lesson {
478        key: format!("experiment:{}", plan.id),
479        once: true,
480        week,
481        playbook: job_playbook(&plan.job, team),
482        line,
483        evidence: Evidence {
484            kind: OutcomeKind::Experiment,
485            summary: format!(
486                "Experiment `{}` on {} stopped on {} after {} looks: {decision}",
487                plan.id,
488                plan.page,
489                at.date_naive(),
490                report.look
491            ),
492            link: format!("{REVIEW_PATH}?week={week}#experiments"),
493        },
494        expected_effect,
495    })
496}
497
498/// The lesson of a KPI short of the owner's target in [`KPI_MISS_WEEKS`] weekly reviews in a
499/// row; `None` otherwise.
500fn kpi_lesson(line: &KpiLine, kpi: &Kpi, week_start: NaiveDate, team: &SiteTeam) -> Option<Lesson> {
501    let review = &line.review;
502    if !matches!(review.phase, KpiPhase::Tracking) {
503        return None;
504    }
505    let (baseline, target) = (review.baseline?, review.target?);
506    let (week, previous) = (review.week?, review.previous_week?);
507    let higher_is_better = match kpi.direction {
508        Direction::Up => true,
509        Direction::Down => false,
510        _ => return None,
511    };
512    let short = |value: f64| if higher_is_better { value < target } else { value > target };
513    if !(short(previous) && short(week)) {
514        return None;
515    }
516    let name = &review.name;
517    let previous_week = week_start - chrono::Duration::days(7);
518    Some(Lesson {
519        key: format!("kpi:{}", review.kpi),
520        once: false,
521        week: week_start,
522        playbook: kpi_playbook(&kpi.metric.0, team),
523        line: format!(
524            "- {name} missed its target of {target:.2} in {KPI_MISS_WEEKS} weekly reviews in a \
525             row ({previous:.2}, then {week:.2}): put the work that moves it first in each run, \
526             and say in the run's report what was done for it."
527        ),
528        evidence: Evidence {
529            kind: OutcomeKind::Kpi,
530            summary: format!(
531                "{name}: {previous:.2} in the week of {previous_week} and {week:.2} in the week \
532                 of {week_start}, against a target of {target:.2} (baseline {baseline:.2})"
533            ),
534            link: format!("{REVIEW_PATH}?week={week_start}#kpis"),
535        },
536        expected_effect: format!("{name} moves back towards its target of {target:.2}"),
537    })
538}
539
540/// What [`PlaybookLearning::open`] builds the learning job from.
541pub struct LearningParts {
542    /// The site.
543    pub site: SiteRef,
544    /// The site's team, which says whose playbooks run.
545    pub team: SiteTeam,
546    /// The person whose decision cards decide proposals.
547    pub owner: String,
548    /// The weekly review it reads the KPIs from.
549    pub composer: ReviewComposer,
550    /// The experiments it reads the decisions from.
551    pub experiments: Arc<ExperimentRunner>,
552    /// The charters, for each KPI's metric and direction.
553    pub charters: Arc<dyn CharterStore>,
554    /// The ladder: the learning job's level, and the owner's decisions on its proposals.
555    pub ladder: AutonomyLadder,
556    /// Where decision cards go: the kernel's approval service.
557    pub approvals: Arc<dyn ApprovalService>,
558    /// The project's `data/`: proposals in `learning/proposals.json`, versions in
559    /// `playbooks/`, the agents' workspaces in `agents/`.
560    pub data: PathBuf,
561}
562
563/// The `playbook-learning` job's code (spec 3.5 §7.15, §7.20): it reads the outcomes, drafts
564/// the proposals and applies the owner's decisions on them.
565pub struct PlaybookLearning {
566    parts: LearningParts,
567    versions: PlaybookVersions,
568    journal: PathBuf,
569    proposals: Mutex<Vec<PlaybookProposal>>,
570    clock: Arc<dyn Clock>,
571}
572
573impl std::fmt::Debug for PlaybookLearning {
574    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
575        f.debug_struct("PlaybookLearning").field("site", &self.parts.site).finish_non_exhaustive()
576    }
577}
578
579impl PlaybookLearning {
580    /// The learning job over `parts`, with the proposals a restart left.
581    ///
582    /// # Errors
583    ///
584    /// A proposals file that does not read.
585    pub fn open(parts: LearningParts) -> Result<Self> {
586        let journal = parts.data.join("learning").join("proposals.json");
587        let proposals = match std::fs::read(&journal) {
588            Ok(bytes) => serde_json::from_slice(&bytes).map_err(config)?,
589            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Vec::new(),
590            Err(error) => return Err(config(format!("{}: {error}", journal.display()))),
591        };
592        let versions =
593            PlaybookVersions::new(parts.data.join("playbooks"), parts.data.join("agents"));
594        Ok(Self {
595            parts,
596            versions,
597            journal,
598            proposals: Mutex::new(proposals),
599            clock: Arc::new(SystemClock),
600        })
601    }
602
603    /// Reads the time from `clock`.
604    #[must_use]
605    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
606        self.clock = clock;
607        self
608    }
609
610    /// The playbooks and their versions.
611    pub fn versions(&self) -> &PlaybookVersions {
612        &self.versions
613    }
614
615    /// Every proposal, oldest first.
616    pub async fn proposals(&self) -> Vec<PlaybookProposal> {
617        self.proposals.lock().await.clone()
618    }
619
620    /// The learning run of the week starting `week_start` (a Monday): composes its review,
621    /// reads every experiment, and drafts the proposals ([`propose`](Self::propose)).
622    ///
623    /// # Errors
624    ///
625    /// A store's error, or the approval service's.
626    pub async fn learn(&self, week_start: NaiveDate) -> Result<Vec<PlaybookProposal>> {
627        let review = self.parts.composer.compose(week_start, ReviewInputs::default()).await?;
628        let experiments = self.parts.experiments.list().await?;
629        self.propose(&review, &experiments).await
630    }
631
632    /// Drafts a proposal for every outcome in `review` and `experiments` with enough evidence
633    /// that has not proposed before, and cards each for the owner unless the learning job is
634    /// at Observe. Returns the new proposals.
635    ///
636    /// # Errors
637    ///
638    /// A store's error, or the approval service's.
639    pub async fn propose(
640        &self,
641        review: &WeeklyReview,
642        experiments: &[ExperimentRecord],
643    ) -> Result<Vec<PlaybookProposal>> {
644        let team = &self.parts.team;
645        let mut lessons: Vec<Lesson> =
646            experiments.iter().filter_map(|record| experiment_lesson(record, team)).collect();
647        let site = self.parts.site.id;
648        if let Some(current) = self.parts.charters.current(site).await.map_err(config)? {
649            for line in &review.kpis {
650                let kpi = current.charter.kpis.iter().find(|kpi| kpi.id == line.review.kpi);
651                if let Some(lesson) =
652                    kpi.and_then(|kpi| kpi_lesson(line, kpi, review.week_start, team))
653                {
654                    lessons.push(lesson);
655                }
656            }
657        }
658        let level = self
659            .parts
660            .ladder
661            .level(site, LEARNING_JOB)
662            .await
663            .map_err(config)?
664            .unwrap_or(AutonomyLevel::Propose);
665        let now = self.clock.now();
666        let interval = chrono::Duration::days(KPI_PROPOSAL_INTERVAL_DAYS);
667        let mut proposals = self.proposals.lock().await;
668        let mut drafted = Vec::new();
669        for lesson in lessons {
670            let taken = proposals
671                .iter()
672                .any(|p| p.key == lesson.key && (lesson.once || now - p.created_at < interval));
673            if taken {
674                continue;
675            }
676            let current = self.versions.current(lesson.playbook).await?;
677            if current.text.contains(&lesson.line) {
678                continue;
679            }
680            let text = revise(&current.text, &lesson.line);
681            let id =
682                format!("site-playbook-{site}-{}-{}", lesson.key.replace(':', "-"), lesson.week);
683            let mut proposal = PlaybookProposal {
684                id: id.clone(),
685                site,
686                key: lesson.key,
687                playbook: lesson.playbook.to_string(),
688                base_version: current.version,
689                diff: diff(lesson.playbook, &current.text, &text),
690                addition: lesson.line,
691                text,
692                evidence: vec![lesson.evidence],
693                expected_effect: lesson.expected_effect,
694                state: ProposalState::Reported,
695                card: None,
696                version: None,
697                edited: false,
698                decided_by: None,
699                created_at: now,
700                decided_at: None,
701            };
702            // At Observe the job's output goes to reports; from Propose up every revision is
703            // the owner's decision, never applied by the job (spec 3.5 §7.11, §7.15, A-I13).
704            if level != AutonomyLevel::Observe {
705                self.card(&proposal).await?;
706                proposal.state = ProposalState::Proposed;
707                proposal.card = Some(id);
708            }
709            tracing::info!(website.playbook = %proposal.playbook, website.proposal = %proposal.id, website.proposal.state = ?proposal.state, "a playbook revision is proposed");
710            proposals.push(proposal.clone());
711            drafted.push(proposal);
712        }
713        if !drafted.is_empty() {
714            write_json(&self.journal, &*proposals).await?;
715        }
716        Ok(drafted)
717    }
718
719    /// Submits `proposal`'s decision card, or finds the one submitted before a restart.
720    async fn card(&self, proposal: &PlaybookProposal) -> Result<()> {
721        if self.parts.approvals.get(&proposal.id).await?.is_some() {
722            return Ok(());
723        }
724        let summary = format!(
725            "Revise the {} playbook: {}. Evidence: {}. Accept, edit or decline it.",
726            proposal.playbook,
727            proposal.expected_effect,
728            proposal.evidence.iter().map(|e| e.summary.as_str()).collect::<Vec<_>>().join("; ")
729        );
730        let args = json!({
731            "playbook": proposal.playbook,
732            "baseVersion": proposal.base_version,
733            "diff": proposal.diff,
734            "text": proposal.text,
735            "evidence": proposal.evidence,
736            "expectedEffect": proposal.expected_effect,
737        });
738        let call = ToolConfirmationRequest::new(PLAYBOOK_REVISION, args);
739        let owner = self.parts.owner.clone();
740        let scope =
741            ApprovalScope::new(self.parts.site.name.clone(), owner.clone(), "playbook-learning");
742        let policy = ApprovalPolicy::new([ApproverSelector::human(owner)]);
743        let request = ApprovalRequest::new(proposal.id.clone(), scope, &call, policy)
744            .with_summary(summary)
745            .with_risk(ApprovalRisk::Low)
746            .with_allowed_actions([
747                ApprovalAction::Approve,
748                ApprovalAction::Edit,
749                ApprovalAction::Reject,
750            ]);
751        self.parts.approvals.submit(request).await?;
752        Ok(())
753    }
754
755    /// Applies the owner's decided cards (spec 3.5 §7.15): an approval makes the proposed
756    /// text the playbook's next version, an edit makes the owner's `text` it, a refusal or an
757    /// expiry changes nothing; each person's decision counts on the ladder for the learning
758    /// job. Returns the proposals it decided.
759    ///
760    /// # Errors
761    ///
762    /// The approval service's error, or the versions' or the journal's.
763    pub async fn step(&self) -> Result<Vec<PlaybookProposal>> {
764        let mut proposals = self.proposals.lock().await;
765        let mut decided = Vec::new();
766        for proposal in proposals.iter_mut() {
767            if proposal.state != ProposalState::Proposed {
768                continue;
769            }
770            let Some(card) = proposal.card.clone() else { continue };
771            let Some(request) = self.parts.approvals.get(&card).await? else { continue };
772            let decision = request.decisions.last();
773            let now = self.clock.now();
774            let outcome = match request.state {
775                ApprovalState::Pending | ApprovalState::Responded => continue,
776                ApprovalState::Expired | ApprovalState::Cancelled => None,
777                ApprovalState::Rejected => Some(DecisionOutcome::Rejected),
778                ApprovalState::Approved => {
779                    let edited = decision
780                        .filter(|d| d.kind == ApprovalAction::Edit)
781                        .and_then(|d| d.edited_args.as_ref())
782                        .and_then(|args| args.get("text"))
783                        .and_then(Value::as_str)
784                        .map(str::to_string);
785                    let current = self.versions.current(&proposal.playbook).await?;
786                    let text = match &edited {
787                        Some(text) => text.clone(),
788                        None if current.version == proposal.base_version => proposal.text.clone(),
789                        // Another revision was accepted first: the line goes onto it.
790                        None => revise(&current.text, &proposal.addition),
791                    };
792                    let by = decision.map_or(self.parts.owner.as_str(), |d| d.approver.id.as_str());
793                    let version = self
794                        .versions
795                        .accept(&proposal.playbook, &text, &proposal.id, by, now)
796                        .await?;
797                    proposal.version = Some(version.version);
798                    proposal.edited = edited.is_some();
799                    proposal.text = text;
800                    Some(if proposal.edited {
801                        DecisionOutcome::ApprovedWithEdits
802                    } else {
803                        DecisionOutcome::ApprovedUnchanged
804                    })
805                }
806            };
807            proposal.state = match outcome {
808                Some(DecisionOutcome::ApprovedUnchanged | DecisionOutcome::ApprovedWithEdits) => {
809                    ProposalState::Accepted
810                }
811                _ => ProposalState::Declined,
812            };
813            proposal.decided_by = decision.map(|d| d.approver.id.clone());
814            proposal.decided_at = Some(decision.map_or(now, |d| d.decided_at));
815            if let (Some(outcome), Some(decision)) = (outcome, decision) {
816                let recorded = self
817                    .parts
818                    .ladder
819                    .record_decision(JobDecision::new(
820                        self.parts.site.id,
821                        LEARNING_JOB,
822                        card.clone(),
823                        outcome,
824                        decision.approver.clone(),
825                        decision.decided_at,
826                    ))
827                    .await;
828                if let Err(error) = recorded {
829                    tracing::warn!(website.proposal = %proposal.id, error = %error, "the owner's decision on a playbook proposal is not on the ladder");
830                }
831            }
832            tracing::info!(website.playbook = %proposal.playbook, website.proposal = %proposal.id, website.proposal.state = ?proposal.state, "the owner decided a playbook proposal");
833            decided.push(proposal.clone());
834        }
835        if !decided.is_empty() {
836            write_json(&self.journal, &*proposals).await?;
837        }
838        Ok(decided)
839    }
840
841    /// The standing trigger of the weekly learning run on `expr` (six fields, UTC), on the
842    /// maintenance queue of app `app_name`.
843    pub fn trigger(&self, app_name: &str, expr: &str) -> Trigger {
844        let site = self.parts.site.id;
845        let run = NewRun::new(
846            QueueClass::MAINTENANCE,
847            app_name,
848            "website:learning",
849            LEARNING_WORKFLOW,
850            json!({ "site": site }),
851        );
852        Trigger::new(
853            format!("{LEARNING_WORKFLOW}:{site}"),
854            Wake::Cron { expr: expr.to_string(), missed: MissedFirePolicy::FireOnce },
855            run,
856        )
857    }
858
859    /// The learning run: the proposals of last week's review, named in its output.
860    ///
861    /// # Errors
862    ///
863    /// As [`learn`](Self::learn).
864    pub async fn run(&self) -> Result<Value> {
865        let week = monday(self.clock.now().date_naive()) - chrono::Duration::days(7);
866        let drafted = self.learn(week).await?;
867        Ok(json!({
868            "week": week,
869            "proposals": drafted.iter().map(|p| json!({
870                "id": p.id,
871                "playbook": p.playbook,
872                "state": p.state,
873            })).collect::<Vec<_>>(),
874        }))
875    }
876
877    /// Applies the owner's decisions every `idle` until aborted.
878    pub fn spawn(self: Arc<Self>, idle: Duration) -> JoinHandle<()> {
879        tokio::spawn(async move {
880            loop {
881                if let Err(error) = self.step().await {
882                    tracing::warn!(error = %error, "the learning job's step failed");
883                }
884                tokio::time::sleep(idle).await;
885            }
886        })
887    }
888}
889
890#[cfg(test)]
891mod tests {
892    use super::*;
893
894    #[test]
895    fn a_revision_is_a_diff_of_one_added_line() {
896        let before = "# SEO\n\nWrite titles.\n";
897        let after = revise(before, "- Prefer short titles.");
898        let diff = diff("seo", before, &after);
899        assert!(diff.starts_with("--- a/seo.md\n+++ b/seo.md\n"), "{diff}");
900        let added: Vec<&str> =
901            diff.lines().filter(|l| l.starts_with('+') && !l.starts_with("+++")).collect();
902        assert_eq!(added, ["+", "+## Learned", "+", "+- Prefer short titles."]);
903        assert!(!diff.lines().any(|l| l.starts_with('-') && !l.starts_with("---")));
904    }
905
906    #[test]
907    fn weeks_start_on_monday() {
908        let thursday = NaiveDate::from_ymd_opt(2026, 10, 29).unwrap();
909        assert_eq!(monday(thursday), NaiveDate::from_ymd_opt(2026, 10, 26).unwrap());
910        assert_eq!(monday(monday(thursday)), monday(thursday));
911    }
912}