Skip to main content

universal_exports/
agents.rs

1//! The Agents of an Operation and their records: what each has done there, at which
2//! clearance, and which models occupied its codename.
3//!
4//! Records come from the Registry, where Stations count each Mission's outcome and each
5//! incident. The Agents posted to the Operation come from the Headquarters Station's
6//! check-in, so an Agent with no record yet is listed too, with the clearance it works at
7//! there. Reading needs `agent.read` on the Operation; what the Agent's roster record says of its
8//! handler and model also needs `roster.read`, so that action alone decides who reads a record.
9//!
10//! A person with `agent.configure` may lower an Agent's clearance in the Operation or remove
11//! its grant, returning it to its configured clearance; raising one is never done here: it
12//! takes a green ink approval of M's promotion request. Each change is audited first.
13
14use std::collections::BTreeMap;
15use std::time::Duration;
16
17use ai6::directorates::registry::backend::*;
18use ai6::wire::agents::LowerClearance;
19use ai6::{
20    AgentRecord, AgentTally, ApprovalRequest, AuditRecord, CLEARANCE_KIND, ClearanceGrant,
21    ModelTenure, NO_OPERATION, RosterHold, Scorecard, ScorecardPolicy,
22};
23use ai6_diptel::OperationId;
24use axum::Json;
25use axum::extract::{Path, State};
26use axum::http::HeaderMap;
27use serde::{Deserialize, Serialize};
28use uuid::Uuid;
29
30use crate::{
31    ApiError, Gateway, GatewayError, authorize_operation_action, bearer,
32    ensure_operation_registered, resolve_user, resource_action_allowed, unix_timestamp,
33};
34
35const CLEARANCES: [&str; 3] = ["desk", "field", "00"];
36
37/// One Agent of an Operation and its record there.
38#[non_exhaustive]
39#[derive(Debug, Clone, PartialEq, Serialize)]
40pub struct AgentView {
41    /// The Agent codename.
42    pub agent: String,
43    /// Whether the Headquarters Station's roster posts it to the Operation.
44    pub posted: bool,
45    /// Its outcomes in this Operation.
46    pub operation: AgentTally,
47    /// Its outcomes outside any Operation, and quarantines in every Operation.
48    pub every_operation: AgentTally,
49    /// Its outcomes in this Operation by the clearance it worked at.
50    pub by_clearance: BTreeMap<String, AgentTally>,
51    /// When its latest Mission in this Operation ended, as Unix seconds.
52    pub last_mission_at: Option<f64>,
53    /// The models that occupied the codename in this Operation, oldest first, with what each
54    /// did here. A model that has finished no Mission here is not among them.
55    pub model_history: Vec<ModelTenure>,
56    /// How its roster record says it reaches its model, from the Headquarters Station's check-in.
57    /// Empty for an Agent the check-in does not post, and for a person without `roster.read`.
58    pub routes: Vec<AgentRoute>,
59    /// Its retirement, from the Headquarters Station's check-in, once it is near or due.
60    pub retirement: Option<RetirementNotice>,
61    /// The clearance it works at in this Operation, from the Headquarters Station's check-in.
62    pub clearance: Option<String>,
63    /// Its configured clearance, from the same check-in.
64    pub configured_clearance: Option<String>,
65    /// Its clearance grant in this Operation, raised by green ink or lowered by a person.
66    pub grant: Option<ClearanceGrant>,
67    /// M's promotion request for it waiting for green ink, if any.
68    pub promotion: Option<ApprovalRequest>,
69    /// Holds that keep it, or a route of it, out of use here until a person lifts them. A hold
70    /// on one route is left out for a person without `roster.read`.
71    pub holds: Vec<RosterHold>,
72    /// Its grant could not be read: Stations work it at `desk`, and so does this view.
73    pub grant_unreadable: bool,
74    /// Why it is quarantined here, who quarantined it and when, while it is: the record of this
75    /// Operation or of every Operation.
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub quarantined: Option<QuarantineNotice>,
78}
79
80/// A quarantine as the Agent's view states it.
81#[non_exhaustive]
82#[derive(Debug, Clone, PartialEq, Serialize)]
83pub struct QuarantineNotice {
84    /// Why it was quarantined.
85    pub reason: String,
86    /// Who quarantined it: a person, or `station:ID`.
87    pub by: String,
88    /// When, as Unix seconds.
89    pub at: f64,
90    /// Whether the record covers every Operation.
91    pub every_operation: bool,
92}
93
94/// One way an Agent's roster record says it reaches its model.
95#[non_exhaustive]
96#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
97pub struct AgentRoute {
98    /// The AgentHandler provider, when the record names one.
99    pub handler: Option<String>,
100    /// The model; `None` when the record sets none, so the handler's default.
101    pub model: Option<String>,
102    /// The account pool the route names, when it names one.
103    pub pool: Option<String>,
104}
105
106/// An Agent whose `retire_on` date is near or has come.
107#[non_exhaustive]
108#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
109pub struct RetirementNotice {
110    /// The UTC date, `YYYY-MM-DD`.
111    pub retire_on: String,
112    /// `desk` or `retired`.
113    pub on_retire: String,
114    /// `retiring` (within the warning window), `desk_duty` or `retired`.
115    pub status: String,
116}
117
118impl AgentView {
119    fn new(agent: String, posted: bool, record: Option<&AgentRecord>, operation: &str) -> Self {
120        let here = record
121            .map(|record| record.in_operation(operation))
122            .unwrap_or_default();
123        Self {
124            agent,
125            posted,
126            operation: here.tally,
127            every_operation: record
128                .map(|record| record.in_operation(NO_OPERATION).tally)
129                .unwrap_or_default(),
130            by_clearance: here.by_clearance,
131            last_mission_at: here.last_mission_at,
132            model_history: here.model_history,
133            routes: Vec::new(),
134            retirement: None,
135            clearance: None,
136            configured_clearance: None,
137            grant: None,
138            promotion: None,
139            holds: Vec::new(),
140            grant_unreadable: false,
141            quarantined: None,
142        }
143    }
144}
145
146/// What the Headquarters Station's check-in says of the roster.
147#[derive(Default)]
148struct Headquarters {
149    retirements: Vec<ai6::wire::AgentRetirement>,
150    policies: BTreeMap<String, ai6::OperationPolicy>,
151    clearances: BTreeMap<String, BTreeMap<String, ai6::wire::AgentClearance>>,
152}
153
154impl Headquarters {
155    fn read(registry: &dyn RegistryBackend) -> Result<Self, ApiError> {
156        let Some(headquarters) = registry.headquarters().map_err(|_| ApiError::internal())? else {
157            return Ok(Self::default());
158        };
159        let stations = registry
160            .stations(Duration::MAX)
161            .map_err(|_| ApiError::internal())?;
162        Ok(stations
163            .into_iter()
164            .find(|station| station.station() == headquarters.station())
165            .map(|station| {
166                let check_in = station.into_check_in();
167                Self {
168                    policies: check_in.operation_policies.unwrap_or_default(),
169                    clearances: check_in.agent_clearances,
170                    retirements: check_in.retirements.unwrap_or_default(),
171                }
172            })
173            .unwrap_or_default())
174    }
175
176    /// The scorecard settings the check-in says `operation` has; the defaults before it has
177    /// checked in.
178    fn scorecard_policy(&self, operation: &str) -> ScorecardPolicy {
179        self.policies
180            .get(operation)
181            .map(|policy| policy.scorecard)
182            .unwrap_or_default()
183    }
184
185    /// The Agents posted to the Operation.
186    fn posted(&self, operation: &str) -> Vec<String> {
187        self.policies
188            .get(operation)
189            .into_iter()
190            .flat_map(|policy| &policy.agents)
191            .map(|agent| agent.id.clone())
192            .collect()
193    }
194
195    /// How the check-in's roster says the Agent reaches its model in the Operation.
196    fn routes(&self, operation: &str, agent: &str) -> Vec<AgentRoute> {
197        self.policies
198            .get(operation)
199            .into_iter()
200            .flat_map(|policy| &policy.agents)
201            .filter(|entry| entry.id == agent)
202            .flat_map(|entry| {
203                if entry.routes.is_empty() {
204                    vec![AgentRoute {
205                        handler: entry.handler.clone(),
206                        model: entry.model.clone(),
207                        pool: None,
208                    }]
209                } else {
210                    entry
211                        .routes
212                        .iter()
213                        .map(|route| AgentRoute {
214                            handler: Some(route.handler.clone()),
215                            model: route.model.clone(),
216                            pool: route.pool.clone(),
217                        })
218                        .collect()
219                }
220            })
221            .collect()
222    }
223
224    /// The clearance the Agent works at in the Operation and its configured one.
225    fn clearance(&self, operation: &str, agent: &str) -> (Option<String>, Option<String>) {
226        self.clearances
227            .get(operation)
228            .and_then(|agents| agents.get(agent))
229            .map(|entry| (entry.clearance.clone(), entry.configured.clone()))
230            .unwrap_or_default()
231    }
232
233    /// The codename stands for a posted Agent's codename or a unique alias.
234    fn codename(&self, operation: &str, name: &str) -> Option<String> {
235        let agents = self.clearances.get(operation)?;
236        if agents.contains_key(name) {
237            return Some(name.to_owned());
238        }
239        let mut matches = agents
240            .iter()
241            .filter(|(_, entry)| entry.aliases.iter().any(|alias| alias == name));
242        let (codename, _) = matches.next()?;
243        matches.next().is_none().then(|| codename.clone())
244    }
245
246    /// Whether the check-in says the Agent's grant in the Operation could not be read.
247    fn unreadable(&self, operation: &str, agent: &str) -> bool {
248        self.clearances
249            .get(operation)
250            .and_then(|agents| agents.get(agent))
251            .is_some_and(|entry| entry.unreadable)
252    }
253
254    /// The Agent's retirement notice, if the check-in lists one.
255    fn retirement(&self, agent: &str) -> Option<RetirementNotice> {
256        self.retirements
257            .iter()
258            .find(|notice| notice.agent == agent)
259            .map(|notice| RetirementNotice {
260                retire_on: notice.retire_on.clone(),
261                on_retire: notice.on_retire.as_str().to_owned(),
262                status: notice.status.as_str().to_owned(),
263            })
264    }
265}
266
267/// `GET /v1/user/operations/{operation_id}/agents`: every Agent posted to the Operation or
268/// with a record there, by codename.
269pub(crate) async fn list(
270    State(gateway): State<Gateway>,
271    headers: HeaderMap,
272    Path(operation_id): Path<String>,
273) -> Result<Json<Vec<AgentView>>, ApiError> {
274    let person = resolve_user(&gateway, bearer(&headers)?).await?;
275    let operation_id = OperationId::new(operation_id).map_err(|_| ApiError::bad_request())?;
276    authorize_operation_action(&gateway, person.clone(), &operation_id, "agent.read").await?;
277    let reads_roster = resource_action_allowed(
278        &gateway,
279        person,
280        crate::roster::ROSTER_RESOURCE.to_owned(),
281        "roster.read",
282    )
283    .await?;
284    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
285    ensure_operation_registered(&registry, &operation_id).await?;
286    let operation = operation_id.to_string();
287    let views = tokio::task::spawn_blocking(move || {
288        let headquarters = Headquarters::read(registry.as_ref())?;
289        let posted = headquarters.posted(&operation);
290        let records = registry.agent_records().map_err(|_| ApiError::internal())?;
291        let mut views = BTreeMap::new();
292        for agent in posted {
293            let record = records.iter().find(|record| record.agent == agent);
294            views.insert(
295                agent.clone(),
296                AgentView::new(agent, true, record, &operation),
297            );
298        }
299        for record in &records {
300            if !views.contains_key(&record.agent) && record.by_operation.contains_key(&operation) {
301                views.insert(
302                    record.agent.clone(),
303                    AgentView::new(record.agent.clone(), false, Some(record), &operation),
304                );
305            }
306        }
307        let promotions = registry
308            .pending_approvals(&operation, unix_timestamp()?)
309            .map_err(|_| ApiError::internal())?
310            .into_iter()
311            .filter(is_promotion)
312            .collect::<Vec<_>>();
313        let holds = registry
314            .holds(&operation)
315            .map_err(|_| ApiError::internal())?;
316        let quarantines = registry.quarantines().map_err(|_| ApiError::internal())?;
317        for view in views.values_mut() {
318            view.quarantined = quarantines
319                .iter()
320                .find(|record| record.covers(&view.agent, Some(&operation)))
321                .map(|record| QuarantineNotice {
322                    reason: record.reason.clone(),
323                    by: record.by.clone(),
324                    at: record.at,
325                    every_operation: record.operation.is_none(),
326                });
327            view.holds = holds
328                .iter()
329                .filter(|hold| hold.agent == view.agent && (reads_roster || hold.holds_agent()))
330                .cloned()
331                .collect();
332            view.retirement = headquarters.retirement(&view.agent);
333            if reads_roster {
334                view.routes = headquarters.routes(&operation, &view.agent);
335            }
336            (view.clearance, view.configured_clearance) =
337                headquarters.clearance(&operation, &view.agent);
338            match registry.clearance_grant(&operation, &view.agent) {
339                Ok(grant) => view.grant = grant,
340                // A codename that is not a Registry key has no grant.
341                Err(error) if error.kind() == std::io::ErrorKind::InvalidInput => {}
342                Err(_) => {
343                    view.grant_unreadable = true;
344                    view.clearance = Some("desk".to_owned());
345                }
346            }
347            if headquarters.unreadable(&operation, &view.agent) {
348                view.grant_unreadable = true;
349            }
350            view.promotion = promotions
351                .iter()
352                .find(|request| request.agent == view.agent)
353                .cloned();
354        }
355        Ok::<_, ApiError>(views.into_values().collect::<Vec<_>>())
356    })
357    .await
358    .map_err(|_| ApiError::internal())??;
359    Ok(Json(views))
360}
361
362/// The query of `DELETE .../agents/{agent}/hold`.
363#[derive(Deserialize)]
364#[serde(deny_unknown_fields)]
365pub(crate) struct HoldQuery {
366    /// With `handler`, lifts the hold on that one route; without, the hold on the whole Agent.
367    handler: Option<String>,
368    model: Option<String>,
369    pool: Option<String>,
370}
371
372/// `DELETE /v1/user/operations/{operation_id}/agents/{agent}/hold`: lifts the hold on the Agent,
373/// or on the route the query names, so selection takes it again. Needs `agent.configure`; audited
374/// first as `agent.hold.lifted`. `404` when there is no such hold.
375pub(crate) async fn lift_hold(
376    State(gateway): State<Gateway>,
377    headers: HeaderMap,
378    Path((operation_id, agent)): Path<(String, String)>,
379    axum::extract::Query(query): axum::extract::Query<HoldQuery>,
380) -> Result<Json<RosterHold>, ApiError> {
381    valid_agent(&agent)?;
382    let person = resolve_user(&gateway, bearer(&headers)?).await?;
383    let operation_id = OperationId::new(operation_id).map_err(|_| ApiError::bad_request())?;
384    authorize_operation_action(&gateway, person.clone(), &operation_id, "agent.configure").await?;
385    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
386    ensure_operation_registered(&registry, &operation_id).await?;
387    let route = match (query.handler, query.model, query.pool) {
388        (Some(handler), model, pool) => Some(ai6::RouteRef::new(handler, model, pool)),
389        (None, None, None) => None,
390        _ => return Err(ApiError::bad_request()),
391    };
392    let agent = resolve(&registry, &operation_id, &agent)
393        .await?
394        .unwrap_or(agent);
395    let now = unix_timestamp()?;
396    let (store, operation, name, held) = (
397        registry.clone(),
398        operation_id.to_string(),
399        agent.clone(),
400        route.clone(),
401    );
402    let current = tokio::task::spawn_blocking(move || store.holds(&operation))
403        .await
404        .map_err(|_| ApiError::internal())?
405        .map_err(|_| ApiError::internal())?
406        .into_iter()
407        .find(|hold| hold.agent == name && hold.route == held)
408        .ok_or_else(|| ApiError::from(GatewayError::NotFound))?;
409    audit(
410        registry.clone(),
411        person.id.clone(),
412        "agent.hold.lifted",
413        operation_id.to_string(),
414        ai6::hold_target(&agent, route.as_ref(), operation_id.as_str()),
415        now,
416    )
417    .await?;
418    let (operation, name) = (operation_id.to_string(), agent);
419    let lifted =
420        tokio::task::spawn_blocking(move || registry.lift_hold(&operation, &name, route.as_ref()))
421            .await
422            .map_err(|_| ApiError::internal())?
423            .map_err(|_| ApiError::internal())?
424            .unwrap_or(current);
425    Ok(Json(lifted))
426}
427
428/// The query of `GET .../agents/scorecard`.
429#[derive(Deserialize)]
430#[serde(deny_unknown_fields)]
431pub(crate) struct ScorecardQuery {
432    /// Days to cover instead of the Operation's setting; 0 covers every run on record.
433    window_days: Option<u64>,
434}
435
436/// `GET /v1/user/operations/{operation_id}/agents/scorecard`: how each Agent, route and model
437/// ran the Operation's Missions over the window, with the runs behind every number. Needs
438/// `agent.read` on the Operation and `roster.read`, since it shows which handler and model each
439/// Agent ran on.
440pub(crate) async fn scorecard(
441    State(gateway): State<Gateway>,
442    headers: HeaderMap,
443    Path(operation_id): Path<String>,
444    axum::extract::Query(query): axum::extract::Query<ScorecardQuery>,
445) -> Result<Json<Scorecard>, ApiError> {
446    let person = resolve_user(&gateway, bearer(&headers)?).await?;
447    let operation_id = OperationId::new(operation_id).map_err(|_| ApiError::bad_request())?;
448    authorize_operation_action(&gateway, person.clone(), &operation_id, "agent.read").await?;
449    if !resource_action_allowed(
450        &gateway,
451        person,
452        crate::roster::ROSTER_RESOURCE.to_owned(),
453        "roster.read",
454    )
455    .await?
456    {
457        return Err(ApiError::forbidden());
458    }
459    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
460    ensure_operation_registered(&registry, &operation_id).await?;
461    let operation = operation_id.to_string();
462    let now = unix_timestamp()?;
463    let card = tokio::task::spawn_blocking(move || {
464        let mut policy = Headquarters::read(registry.as_ref())?.scorecard_policy(&operation);
465        if let Some(days) = query.window_days {
466            policy.window_days = days;
467        }
468        let runs = registry.runs().map_err(|_| ApiError::internal())?;
469        let mut usage = BTreeMap::new();
470        let missions = runs
471            .iter()
472            .filter(|run| run.operation.as_deref() == Some(operation.as_str()))
473            .map(|run| run.mission_id.as_str())
474            .collect::<std::collections::BTreeSet<_>>();
475        for mission in missions {
476            if let Some(ledger) = registry
477                .mission_usage(Some(&operation), mission)
478                .map_err(|_| ApiError::internal())?
479            {
480                usage.extend(ledger.runs);
481            }
482        }
483        Ok::<_, ApiError>(Scorecard::build(&operation, &runs, &usage, &policy, now))
484    })
485    .await
486    .map_err(|_| ApiError::internal())??;
487    Ok(Json(card))
488}
489
490/// Whether a waiting request is M's promotion request: kind `clearance`, filed under Run
491/// `m` and Mission `promotion-AGENT` for that Agent. A `clearance` request an Agent filed itself
492/// is not one, and is never shown as one.
493fn is_promotion(request: &ApprovalRequest) -> bool {
494    request.scope.kind == CLEARANCE_KIND
495        && request.run.as_str() == "m"
496        && request.mission.as_str() == format!("promotion-{}", request.agent)
497        && request
498            .scope
499            .target
500            .strip_prefix(&request.agent)
501            .is_some_and(|rest| rest.starts_with(':'))
502}
503
504fn valid_agent(agent: &str) -> Result<(), ApiError> {
505    if agent.is_empty()
506        || agent.len() > 128
507        || !agent
508            .bytes()
509            .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte))
510    {
511        return Err(ApiError::bad_request());
512    }
513    Ok(())
514}
515
516async fn audit(
517    registry: std::sync::Arc<dyn RegistryBackend>,
518    actor: String,
519    action: &'static str,
520    operation: String,
521    target: String,
522    at: f64,
523) -> Result<(), ApiError> {
524    let record = AuditRecord {
525        id: Uuid::new_v4().to_string(),
526        actor,
527        action: action.to_owned(),
528        operation,
529        resource: None,
530        target,
531        at,
532    };
533    tokio::task::spawn_blocking(move || registry.record_audit(&record))
534        .await
535        .map_err(|_| ApiError::internal())?
536        .map_err(|_| ApiError::internal())
537}
538
539/// The codename `name` stands for in the Operation, from the Headquarters Station's check-in.
540async fn resolve(
541    registry: &std::sync::Arc<dyn RegistryBackend>,
542    operation: &OperationId,
543    name: &str,
544) -> Result<Option<String>, ApiError> {
545    let (registry, operation, name) = (registry.clone(), operation.to_string(), name.to_owned());
546    tokio::task::spawn_blocking(move || {
547        Ok(Headquarters::read(registry.as_ref())?.codename(&operation, &name))
548    })
549    .await
550    .map_err(|_| ApiError::internal())?
551}
552
553/// Withdraws the approval a replaced or removed grant was raised by, while it is live.
554fn withdraw_raise(
555    registry: &dyn RegistryBackend,
556    previous: Option<&ClearanceGrant>,
557    by: &str,
558    at: f64,
559) {
560    if let Some(grant) = previous
561        && let Some(approval) = grant.approval.as_deref()
562    {
563        // Best effort: M applies an approval once, so the removed grant stays removed either way.
564        let _ = registry.revoke_approval(
565            &grant.operation,
566            approval,
567            &ai6::Revocation::new(by, at, None),
568        );
569    }
570}
571
572/// `PUT /v1/user/operations/{operation_id}/agents/{agent}/clearance`: holds the Agent at the
573/// given clearance or below in the Operation, replacing any grant it had there.
574pub(crate) async fn lower(
575    State(gateway): State<Gateway>,
576    headers: HeaderMap,
577    Path((operation_id, agent)): Path<(String, String)>,
578    Json(request): Json<LowerClearance>,
579) -> Result<Json<ClearanceGrant>, ApiError> {
580    valid_agent(&agent)?;
581    let reason = request.reason.trim().to_owned();
582    if !CLEARANCES.contains(&request.clearance.as_str())
583        || reason.is_empty()
584        || !gateway
585            .config
586            .unex()
587            .text
588            .agent_reason_chars
589            .allows(reason.chars().count())
590        || reason.chars().any(char::is_control)
591        || request.expires_in_secs.is_some_and(|secs| {
592            secs == 0
593                || !gateway
594                    .config
595                    .unex()
596                    .text
597                    .green_ink_max_grant
598                    .allows(std::time::Duration::from_secs(secs))
599        })
600    {
601        return Err(ApiError::bad_request());
602    }
603    let person = resolve_user(&gateway, bearer(&headers)?).await?;
604    let operation_id = OperationId::new(operation_id).map_err(|_| ApiError::bad_request())?;
605    authorize_operation_action(&gateway, person.clone(), &operation_id, "agent.configure").await?;
606    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
607    ensure_operation_registered(&registry, &operation_id).await?;
608    // A grant is kept under the codename Stations read; an unknown name is refused.
609    let agent = resolve(&registry, &operation_id, &agent)
610        .await?
611        .ok_or_else(|| ApiError::from(GatewayError::NotFound))?;
612    let now = unix_timestamp()?;
613    let mut grant = ClearanceGrant::lower(
614        agent.clone(),
615        operation_id.to_string(),
616        request.clearance.clone(),
617        person.id.clone(),
618        now,
619    )
620    .because(reason);
621    if let Some(secs) = request.expires_in_secs {
622        grant = grant.expiring(now + secs as f64);
623    }
624    // Audited first: a change that cannot be recorded is not made.
625    audit(
626        registry.clone(),
627        person.id.clone(),
628        "agent.clearance.lowered",
629        operation_id.to_string(),
630        format!("{agent} {}", request.clearance),
631        now,
632    )
633    .await?;
634    let stored = grant.clone();
635    tokio::task::spawn_blocking(move || {
636        let previous = registry.clearance_grant(&stored.operation, &stored.agent)?;
637        registry.put_clearance_grant(&stored)?;
638        withdraw_raise(registry.as_ref(), previous.as_ref(), &person.id, now);
639        Ok::<_, std::io::Error>(())
640    })
641    .await
642    .map_err(|_| ApiError::internal())?
643    .map_err(|_| ApiError::internal())?;
644    Ok(Json(grant))
645}
646
647/// `DELETE /v1/user/operations/{operation_id}/agents/{agent}/clearance`: removes the Agent's
648/// grant there, so it works at its configured clearance; a raise is withdrawn for good.
649pub(crate) async fn restore(
650    State(gateway): State<Gateway>,
651    headers: HeaderMap,
652    Path((operation_id, agent)): Path<(String, String)>,
653) -> Result<Json<ClearanceGrant>, ApiError> {
654    valid_agent(&agent)?;
655    let person = resolve_user(&gateway, bearer(&headers)?).await?;
656    let operation_id = OperationId::new(operation_id).map_err(|_| ApiError::bad_request())?;
657    authorize_operation_action(&gateway, person.clone(), &operation_id, "agent.configure").await?;
658    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
659    ensure_operation_registered(&registry, &operation_id).await?;
660    // An Agent no longer posted keeps its codename: its grant can still be removed by it.
661    let agent = resolve(&registry, &operation_id, &agent)
662        .await?
663        .unwrap_or(agent);
664    let now = unix_timestamp()?;
665    let store = registry.clone();
666    let (operation, name) = (operation_id.to_string(), agent.clone());
667    let current = tokio::task::spawn_blocking(move || store.clearance_grant(&operation, &name))
668        .await
669        .map_err(|_| ApiError::internal())?
670        .map_err(|_| ApiError::internal())?
671        .ok_or_else(|| ApiError::from(GatewayError::NotFound))?;
672    audit(
673        registry.clone(),
674        person.id.clone(),
675        "agent.clearance.revoked",
676        operation_id.to_string(),
677        format!("{agent} {}", current.clearance),
678        now,
679    )
680    .await?;
681    let (operation, name) = (operation_id.to_string(), agent);
682    let removed = tokio::task::spawn_blocking(move || {
683        let removed = registry.remove_clearance_grant(&operation, &name)?;
684        withdraw_raise(registry.as_ref(), removed.as_ref(), &person.id, now);
685        Ok::<_, std::io::Error>(removed)
686    })
687    .await
688    .map_err(|_| ApiError::internal())?
689    .map_err(|_| ApiError::internal())?
690    .ok_or_else(|| ApiError::from(GatewayError::NotFound))?;
691    Ok(Json(removed))
692}
693
694#[cfg(test)]
695mod tests {
696
697    use ai6::directorates::registry::backend::*;
698    use ai6::{AgentOutcome, AgentOutcomeReport};
699    use axum::http::StatusCode;
700
701    use crate::controls::tests::served_with;
702
703    /// Operator 007 may read G's Agents; viewer 007 may read its Missions only.
704    const READERS: &str = r#"
705        [role.agent-reader]
706        actions = ["agent.read", "mission.read"]
707
708        [role.viewer]
709        actions = ["mission.read"]
710
711        [[rule]]
712        subject = "person:operator-007"
713        scope = "operation:G"
714        role = "agent-reader"
715
716        [[rule]]
717        subject = "person:viewer-007"
718        scope = "operation:G"
719        role = "viewer"
720    "#;
721
722    async fn agents(base: &str, token: &str) -> reqwest::Response {
723        reqwest::Client::new()
724            .get(format!("{base}/v1/user/operations/G/agents"))
725            .bearer_auth(token)
726            .send()
727            .await
728            .unwrap()
729    }
730
731    #[tokio::test]
732    async fn the_record_is_returned_only_to_agent_read() {
733        let served = served_with(READERS).await;
734        served
735            .registry
736            .check_in(
737                "hq",
738                serde_json::from_value(serde_json::json!({
739                    "operation_policies": {"G": {"operation": "G", "agents": [{"id": "007"}, {"id": "008"}]}},
740                    "retirements": [{"agent": "007", "retire_on": "2027-01-31", "on_retire": "desk", "status": "retiring"}]
741                })).unwrap(),
742            )
743            .unwrap();
744        for (key, outcome) in [
745            ("m-1#3", AgentOutcome::Done),
746            ("m-2#3", AgentOutcome::Done),
747            ("m-3#2", AgentOutcome::Stalled),
748        ] {
749            served
750                .registry
751                .record_agent_outcome(
752                    &AgentOutcomeReport::new("007", Some("G".into()), outcome, key, 10.0)
753                        .at_clearance("field"),
754                )
755                .unwrap();
756        }
757        served
758            .registry
759            .record_agent_outcome(&AgentOutcomeReport::new(
760                "009",
761                Some("L".into()),
762                AgentOutcome::Failed,
763                "m-l#2",
764                11.0,
765            ))
766            .unwrap();
767        served
768            .registry
769            .record_agent_outcome(
770                &AgentOutcomeReport::new(
771                    "007",
772                    Some("L".into()),
773                    AgentOutcome::Done,
774                    "m-l2#1#done",
775                    99.0,
776                )
777                .at_clearance("00")
778                .with_model(Some("haiku".into())),
779            )
780            .unwrap();
781
782        let response = agents(&served.base, &served.viewer).await;
783        assert_eq!(response.status(), StatusCode::FORBIDDEN);
784
785        let response = agents(&served.base, &served.operator).await;
786        assert_eq!(response.status(), StatusCode::OK);
787        let views: serde_json::Value = response.json().await.unwrap();
788        let ids: Vec<_> = views
789            .as_array()
790            .unwrap()
791            .iter()
792            .map(|view| view["agent"].as_str().unwrap())
793            .collect();
794        assert_eq!(
795            ids,
796            ["007", "008"],
797            "another Operation's Agent is not listed"
798        );
799        assert_eq!(views[0]["operation"]["done"], 2);
800        assert_eq!(views[0]["operation"]["stalled"], 1);
801        assert_eq!(views[0]["by_clearance"]["field"]["done"], 2);
802        assert_eq!(
803            views[0]["by_clearance"]["00"],
804            serde_json::Value::Null,
805            "nothing of L"
806        );
807        assert_eq!(views[0]["last_mission_at"], 10.0);
808        assert_eq!(views[0]["model_history"].as_array().unwrap().len(), 1);
809        assert_eq!(views[1]["operation"]["done"], 0);
810        assert_eq!(views[0]["retirement"]["status"], "retiring");
811        assert_eq!(views[1]["retirement"], serde_json::Value::Null);
812    }
813
814    /// Operator 007 may read G's Agents and the roster; viewer 007 may read G's Agents alone.
815    const ROSTER_READERS: &str = r#"
816        [role.agent-reader]
817        actions = ["agent.read"]
818
819        [role.roster-reader]
820        actions = ["roster.read"]
821
822        [[rule]]
823        subject = "person:operator-007"
824        scope = "operation:G"
825        role = "agent-reader"
826
827        [[rule]]
828        subject = "person:operator-007"
829        scope = "config:roster"
830        role = "roster-reader"
831
832        [[rule]]
833        subject = "person:viewer-007"
834        scope = "operation:G"
835        role = "agent-reader"
836    "#;
837
838    #[tokio::test]
839    async fn the_record_s_model_reaches_who_may_read_the_roster_and_nobody_else() {
840        let served = served_with(ROSTER_READERS).await;
841        served
842            .registry
843            .check_in(
844                "hq",
845                serde_json::from_value(serde_json::json!({
846                    "operation_policies": {"G": {"operation": "G", "agents": [
847                                {"id": "no-missions", "handler": "claude", "model": "opus-5", "roles": ["secret-role"]},
848                                {"id": "changed", "handler": "codex", "model": "new-model"},
849                                {"id": "unset", "handler": "claude", "model": null},
850                                {"id": "routed", "handler": null, "model": null, "routes": [
851                                        {"handler": "acp", "model": "grok-4.7", "pool": "grok-free"},
852                                        {"handler": "claude", "model": "gemini-free"},
853                                ]},
854                    ]}}
855                })).unwrap(),
856            )
857            .unwrap();
858        served
859            .registry
860            .record_agent_outcome(
861                &AgentOutcomeReport::new(
862                    "changed",
863                    Some("G".into()),
864                    AgentOutcome::Done,
865                    "m#1",
866                    10.0,
867                )
868                .with_model(Some("old-model".into())),
869            )
870            .unwrap();
871        served
872            .registry
873            .record_agent_outcome(
874                &AgentOutcomeReport::new(
875                    "retired",
876                    Some("G".into()),
877                    AgentOutcome::Done,
878                    "m#2",
879                    11.0,
880                )
881                .with_model(Some("gone-model".into())),
882            )
883            .unwrap();
884
885        let views: serde_json::Value = agents(&served.base, &served.operator)
886            .await
887            .json()
888            .await
889            .unwrap();
890        let view = |agent: &str| {
891            views
892                .as_array()
893                .unwrap()
894                .iter()
895                .find(|view| view["agent"] == agent)
896                .unwrap()
897                .clone()
898        };
899        assert_eq!(
900            view("no-missions")["routes"],
901            serde_json::json!([{"handler": "claude", "model": "opus-5", "pool": null}]),
902            "with no Mission there is no history, and the record still says"
903        );
904        assert_eq!(view("no-missions")["model_history"], serde_json::json!([]));
905        assert_eq!(
906            view("routed")["routes"],
907            serde_json::json!([
908                {"handler": "acp", "model": "grok-4.7", "pool": "grok-free"},
909                {"handler": "claude", "model": "gemini-free", "pool": null},
910            ]),
911            "each route of a routed Agent"
912        );
913        assert_eq!(
914            view("changed")["routes"],
915            serde_json::json!([{"handler": "codex", "model": "new-model", "pool": null}])
916        );
917        assert_eq!(view("changed")["model_history"][0]["model"], "old-model");
918        assert_eq!(
919            view("unset")["routes"],
920            serde_json::json!([{"handler": "claude", "model": null, "pool": null}])
921        );
922        assert_eq!(
923            view("retired")["routes"],
924            serde_json::json!([]),
925            "not posted: no record to read here"
926        );
927
928        let response = agents(&served.base, &served.viewer).await;
929        assert_eq!(response.status(), StatusCode::OK);
930        let text = response.text().await.unwrap();
931        for hidden in ["opus-5", "new-model", "claude", "codex", "secret-role"] {
932            assert!(
933                !text.contains(hidden),
934                "{hidden} without roster.read: {text}"
935            );
936        }
937        let views: serde_json::Value = serde_json::from_str(&text).unwrap();
938        assert_eq!(views[0]["routes"], serde_json::json!([]));
939        let changed = views
940            .as_array()
941            .unwrap()
942            .iter()
943            .find(|view| view["agent"] == "changed")
944            .unwrap();
945        assert_eq!(
946            changed["model_history"][0]["model"], "old-model",
947            "what ran stays hers to read with agent.read"
948        );
949    }
950
951    /// Operator 007 may configure G's Agents and sign green ink; viewer 007 may only sign.
952    const CONFIGURERS: &str = r#"
953        [role.configurer]
954        actions = ["agent.read", "agent.configure", "approval.decide", "mission.read"]
955
956        [role.signer]
957        actions = ["approval.decide", "mission.read"]
958
959        [[rule]]
960        subject = "person:operator-007"
961        scope = "operation:G"
962        role = "configurer"
963
964        [[rule]]
965        subject = "person:viewer-007"
966        scope = "operation:G"
967        role = "signer"
968    "#;
969
970    async fn call(
971        method: reqwest::Method,
972        url: String,
973        token: &str,
974        body: Option<serde_json::Value>,
975    ) -> reqwest::Response {
976        let mut request = reqwest::Client::new()
977            .request(method, url)
978            .bearer_auth(token);
979        if let Some(body) = body {
980            request = request.json(&body);
981        }
982        request.send().await.unwrap()
983    }
984
985    #[tokio::test]
986    async fn a_promotion_needs_agent_configure_to_sign_and_a_person_may_only_lower() {
987        let served = served_with(CONFIGURERS).await;
988        served
989            .registry
990            .check_in(
991                "hq",
992                serde_json::from_value(serde_json::json!({
993                    "operation_policies": {"G": {"operation": "G", "agents": [{"id": "007"}]}},
994                    "agent_clearances": {"G": {"007": {
995                                "clearance": "desk", "configured": "desk", "aliases": ["JamesBond"]
996                    }}}
997                }))
998                .unwrap(),
999            )
1000            .unwrap();
1001        let now = crate::unix_timestamp().ok().unwrap();
1002        let request = ai6::ApprovalRequest::try_new(
1003            "G",
1004            ai6::MissionId::try_new("promotion-007").unwrap(),
1005            ai6::RunId::try_new("m").unwrap(),
1006            "007",
1007            ai6::ActionScope::try_new("clearance", "007:field@G").unwrap(),
1008            "10 Missions done",
1009            "007:field@G#1",
1010            &Default::default(),
1011        )
1012        .unwrap()
1013        .expiring(now, std::time::Duration::from_secs(3600));
1014        served.registry.request_approval(&request).unwrap();
1015        // 007 files a clearance request of its own; it is not M's promotion.
1016        let own = ai6::ApprovalRequest::try_new(
1017            "G",
1018            ai6::MissionId::try_new("mission-g").unwrap(),
1019            ai6::RunId::try_new("run-g").unwrap(),
1020            "007",
1021            ai6::ActionScope::try_new("clearance", "007:00@G").unwrap(),
1022            "let me",
1023            "self",
1024            &Default::default(),
1025        )
1026        .unwrap()
1027        .expiring(now - 1.0, std::time::Duration::from_secs(3600));
1028        served.registry.request_approval(&own).unwrap();
1029
1030        let views: serde_json::Value = agents(&served.base, &served.operator)
1031            .await
1032            .json()
1033            .await
1034            .unwrap();
1035        assert_eq!(views[0]["clearance"], "desk");
1036        assert_eq!(views[0]["promotion"]["id"], request.id.as_str());
1037
1038        let approve = format!(
1039            "{}/v1/user/operations/G/green-ink/{}/approve",
1040            served.base, request.id
1041        );
1042        let refused = call(
1043            reqwest::Method::POST,
1044            approve.clone(),
1045            &served.viewer,
1046            Some(serde_json::json!({})),
1047        )
1048        .await;
1049        assert_eq!(
1050            refused.status(),
1051            StatusCode::FORBIDDEN,
1052            "approval.decide alone"
1053        );
1054        let signed = call(
1055            reqwest::Method::POST,
1056            approve,
1057            &served.operator,
1058            Some(serde_json::json!({})),
1059        )
1060        .await;
1061        assert_eq!(signed.status(), StatusCode::OK);
1062
1063        // M raises 007 with it; revoking the approval takes the raise back, audited.
1064        let raise = ai6::ClearanceGrant::raise(
1065            "007",
1066            "G",
1067            "field",
1068            request.id.clone(),
1069            "operator-007",
1070            now,
1071        )
1072        .for_occupant(None, "desk");
1073        served.registry.put_clearance_grant(&raise).unwrap();
1074        let revoked = call(
1075            reqwest::Method::POST,
1076            format!(
1077                "{}/v1/user/operations/G/green-ink/{}/revoke",
1078                served.base, request.id
1079            ),
1080            &served.operator,
1081            None,
1082        )
1083        .await;
1084        assert_eq!(revoked.status(), StatusCode::OK);
1085        assert!(
1086            served
1087                .registry
1088                .clearance_grant("G", "007")
1089                .unwrap()
1090                .is_none()
1091        );
1092
1093        // An unreadable grant shows as desk, as Stations work it.
1094        let grants = served.directory.path().join("clearance-grants").join("G");
1095        std::fs::create_dir_all(&grants).unwrap();
1096        std::fs::write(grants.join("007.json"), b"{ not a grant").unwrap();
1097        let views: serde_json::Value = agents(&served.base, &served.operator)
1098            .await
1099            .json()
1100            .await
1101            .unwrap();
1102        assert_eq!(views[0]["grant_unreadable"], true);
1103        assert_eq!(views[0]["clearance"], "desk");
1104        std::fs::remove_file(grants.join("007.json")).unwrap();
1105
1106        let clearance = format!("{}/v1/user/operations/G/agents/007/clearance", served.base);
1107        let lower = serde_json::json!({"clearance": "desk", "reason": "rewriting history"});
1108        let refused = call(
1109            reqwest::Method::PUT,
1110            clearance.clone(),
1111            &served.viewer,
1112            Some(lower.clone()),
1113        )
1114        .await;
1115        assert_eq!(refused.status(), StatusCode::FORBIDDEN);
1116        let bad = call(
1117            reqwest::Method::PUT,
1118            clearance.clone(),
1119            &served.operator,
1120            Some(serde_json::json!({"clearance": "cosmic", "reason": "x"})),
1121        )
1122        .await;
1123        assert_eq!(bad.status(), StatusCode::BAD_REQUEST);
1124        let unknown = call(
1125            reqwest::Method::PUT,
1126            format!(
1127                "{}/v1/user/operations/G/agents/nobody/clearance",
1128                served.base
1129            ),
1130            &served.operator,
1131            Some(lower.clone()),
1132        )
1133        .await;
1134        assert_eq!(unknown.status(), StatusCode::NOT_FOUND);
1135        let lowered = call(
1136            reqwest::Method::PUT,
1137            format!(
1138                "{}/v1/user/operations/G/agents/JamesBond/clearance",
1139                served.base
1140            ),
1141            &served.operator,
1142            Some(lower),
1143        )
1144        .await;
1145        assert_eq!(lowered.status(), StatusCode::OK, "by alias");
1146        let grant = served
1147            .registry
1148            .clearance_grant("G", "007")
1149            .unwrap()
1150            .unwrap();
1151        assert!(!grant.raises(), "a person's grant only lowers");
1152        assert_eq!(grant.signer, "operator-007");
1153
1154        let removed = call(
1155            reqwest::Method::DELETE,
1156            clearance.clone(),
1157            &served.operator,
1158            None,
1159        )
1160        .await;
1161        assert_eq!(removed.status(), StatusCode::OK);
1162        assert!(
1163            served
1164                .registry
1165                .clearance_grant("G", "007")
1166                .unwrap()
1167                .is_none()
1168        );
1169        let again = call(reqwest::Method::DELETE, clearance, &served.operator, None).await;
1170        assert_eq!(again.status(), StatusCode::NOT_FOUND);
1171        let actions: Vec<_> = served
1172            .registry
1173            .list_audit(20)
1174            .unwrap()
1175            .into_iter()
1176            .map(|record| record.action)
1177            .collect();
1178        for action in [
1179            "agent.clearance.lowered",
1180            "agent.clearance.revoked",
1181            "green_ink.approved",
1182        ] {
1183            assert!(
1184                actions.contains(&action.to_owned()),
1185                "{action}: {actions:?}"
1186            );
1187        }
1188    }
1189
1190    /// Opens Run `mission`.1 of `agent` on `model`, in `state` with `reason`; closed unless
1191    /// its Mission is blocked.
1192    fn attempt(
1193        served: &crate::controls::tests::Served,
1194        mission: &str,
1195        agent: &str,
1196        model: &str,
1197        state: &str,
1198        reason: Option<&str>,
1199    ) {
1200        use ai6::{NewRun, RunLaunch, RunResult, RunStatus, RunUpdate};
1201        let record = served
1202            .registry
1203            .open_run(
1204                NewRun::new(format!("{mission}.1"), mission, "hq")
1205                    .with_operation("G")
1206                    .with_launch(
1207                        RunLaunch::new("claude", "pipe", "/w")
1208                            .with_model(Some(model.to_owned()), None)
1209                            .with_agent(Some(agent.to_owned())),
1210                    ),
1211                std::time::Duration::from_secs(60),
1212            )
1213            .unwrap();
1214        served
1215            .registry
1216            .update_run(
1217                &record.id,
1218                "hq",
1219                record.fence,
1220                RunUpdate::default()
1221                    .result(RunResult::new(state).with_reason(reason.map(str::to_owned)))
1222                    .status(if state == "blocked" {
1223                        RunStatus::Active
1224                    } else {
1225                        RunStatus::Ended
1226                    }),
1227            )
1228            .unwrap();
1229    }
1230
1231    async fn scorecard(base: &str, token: &str, query: &str) -> reqwest::Response {
1232        reqwest::Client::new()
1233            .get(format!(
1234                "{base}/v1/user/operations/G/agents/scorecard{query}"
1235            ))
1236            .bearer_auth(token)
1237            .send()
1238            .await
1239            .unwrap()
1240    }
1241
1242    #[tokio::test]
1243    async fn the_scorecard_counts_the_agents_own_outcomes_for_who_may_read_the_roster() {
1244        let served = served_with(ROSTER_READERS).await;
1245        served
1246            .registry
1247            .check_in(
1248                "hq",
1249                serde_json::from_value(serde_json::json!({
1250                    "operation_policies": {"G": {"operation": "G", "agents": [{"id": "007"}],
1251                            "scorecard": {"window_days": 7, "small_sample": 2}}}
1252                }))
1253                .unwrap(),
1254            )
1255            .unwrap();
1256        attempt(&served, "m1", "007", "opus", "done", None);
1257        attempt(&served, "m2", "007", "opus", "failed", None);
1258        attempt(&served, "m3", "007", "opus", "abandoned", None);
1259        attempt(&served, "m4", "007", "haiku", "blocked", Some("green-ink"));
1260        served
1261            .registry
1262            .record_usage(
1263                Some("G"),
1264                "m2",
1265                "m2.1",
1266                &ai6::UsageTotals {
1267                    input: 70,
1268                    output: 7,
1269                    cost_micro_usd: 900,
1270                    ..ai6::UsageTotals::default()
1271                },
1272                1,
1273            )
1274            .unwrap();
1275
1276        assert_eq!(
1277            scorecard(&served.base, &served.viewer, "").await.status(),
1278            StatusCode::FORBIDDEN,
1279            "agent.read alone does not show which model each Agent ran on"
1280        );
1281        let card: serde_json::Value = scorecard(&served.base, &served.operator, "")
1282            .await
1283            .json()
1284            .await
1285            .unwrap();
1286        assert_eq!(card["window_days"], 7, "the check-in's setting");
1287        assert_eq!(card["small_sample"], 2);
1288        let seven = &card["agents"][0];
1289        assert_eq!(seven["agent"], "007");
1290        let standing = &seven["standing"];
1291        assert_eq!(standing["judged"], 2);
1292        assert_eq!(standing["failure_rate"], 0.5);
1293        assert_eq!(standing["small_sample"], false);
1294        assert_eq!(standing["runs"]["failed"][0]["mission_id"], "m2");
1295        assert_eq!(standing["runs"]["withdrawn"].as_array().unwrap().len(), 1);
1296        assert_eq!(
1297            standing["runs"]["waiting_on_person"]
1298                .as_array()
1299                .unwrap()
1300                .len(),
1301            1
1302        );
1303        assert_eq!(standing["usage"]["cost_micro_usd"], 900);
1304        let models: Vec<_> = card["models"]
1305            .as_array()
1306            .unwrap()
1307            .iter()
1308            .map(|model| model["model"].as_str())
1309            .collect();
1310        assert_eq!(
1311            models,
1312            [None, Some("haiku"), Some("opus")],
1313            "the Run the fixture's gateway already holds names no model"
1314        );
1315        assert_eq!(
1316            card["unattributed"], 1,
1317            "nor an Agent: counted by model only"
1318        );
1319        assert_eq!(seven["routes"][0]["route"]["handler"], "claude");
1320
1321        let all: serde_json::Value = scorecard(&served.base, &served.operator, "?window_days=0")
1322            .await
1323            .json()
1324            .await
1325            .unwrap();
1326        assert_eq!(all["window_days"], 0, "the request's window wins");
1327        assert!(all["from"].is_null());
1328    }
1329
1330    #[tokio::test]
1331    async fn a_mission_held_by_a_quarantine_shows_the_reason_in_its_detail() {
1332        let served = served_with(CONFIGURERS).await;
1333        served
1334            .registry
1335            .check_in(
1336                "hq",
1337                serde_json::from_value(serde_json::json!({ "operation_policies": {"G": {"operation": "G", "agents": [{"id": "007"}]}} }))
1338                .unwrap(),
1339            )
1340            .unwrap();
1341        let before: serde_json::Value = agents(&served.base, &served.operator)
1342            .await
1343            .json()
1344            .await
1345            .unwrap();
1346        assert!(before[0].get("quarantined").is_none());
1347        served
1348            .registry
1349            .quarantine_agent(&ai6::Quarantine::new(
1350                "007",
1351                None,
1352                "turned by a page",
1353                "station:hq",
1354                1_000.0,
1355            ))
1356            .unwrap();
1357        let views: serde_json::Value = agents(&served.base, &served.operator)
1358            .await
1359            .json()
1360            .await
1361            .unwrap();
1362        assert_eq!(
1363            views[0]["quarantined"],
1364            serde_json::json!({
1365                "reason": "turned by a page", "by": "station:hq", "at": 1000.0,
1366                "every_operation": true,
1367            })
1368        );
1369    }
1370
1371    #[tokio::test]
1372    async fn a_hold_is_shown_signed_for_with_agent_configure_and_lifted_with_it() {
1373        let served = served_with(CONFIGURERS).await;
1374        served
1375            .registry
1376            .check_in(
1377                "hq",
1378                serde_json::from_value(serde_json::json!({ "operation_policies": {"G": {"operation": "G", "agents": [{"id": "007"}]}} }))
1379                .unwrap(),
1380            )
1381            .unwrap();
1382        let now = crate::unix_timestamp().ok().unwrap();
1383        let request = ai6::ApprovalRequest::try_new(
1384            "G",
1385            ai6::MissionId::try_new("hold-007").unwrap(),
1386            ai6::RunId::try_new("m").unwrap(),
1387            "007",
1388            ai6::ActionScope::try_new(ai6::HOLD_KIND, "007@G").unwrap(),
1389            "5 of 6 judged attempts failed",
1390            "007@G#1",
1391            &Default::default(),
1392        )
1393        .unwrap()
1394        .expiring(now, std::time::Duration::from_secs(3600));
1395        served.registry.request_approval(&request).unwrap();
1396
1397        let approve = format!(
1398            "{}/v1/user/operations/G/green-ink/{}/approve",
1399            served.base, request.id
1400        );
1401        assert_eq!(
1402            call(
1403                reqwest::Method::POST,
1404                approve.clone(),
1405                &served.viewer,
1406                Some(serde_json::json!({}))
1407            )
1408            .await
1409            .status(),
1410            StatusCode::FORBIDDEN,
1411            "approval.decide alone cannot sign a hold: it stops an Agent's work"
1412        );
1413        assert_eq!(
1414            call(
1415                reqwest::Method::POST,
1416                approve,
1417                &served.operator,
1418                Some(serde_json::json!({}))
1419            )
1420            .await
1421            .status(),
1422            StatusCode::OK
1423        );
1424
1425        // M turns the signature into a hold, in the signer's name.
1426        let route = ai6::RouteRef::new("claude", Some("opus".to_owned()), None);
1427        served
1428            .registry
1429            .put_hold(
1430                &ai6::RosterHold::new("G", "007", None, "5 of 6 failed", "operator-007", now)
1431                    .signed_through(request.id.clone()),
1432            )
1433            .unwrap();
1434        served
1435            .registry
1436            .put_hold(&ai6::RosterHold::new(
1437                "G",
1438                "007",
1439                Some(route.clone()),
1440                "slow",
1441                "m",
1442                now,
1443            ))
1444            .unwrap();
1445        let views: serde_json::Value = agents(&served.base, &served.operator)
1446            .await
1447            .json()
1448            .await
1449            .unwrap();
1450        let held = views[0]["holds"].as_array().unwrap();
1451        assert_eq!(
1452            held.len(),
1453            1,
1454            "a route hold shows handler and model, which roster.read decides"
1455        );
1456        assert_eq!(held[0]["by"], "operator-007");
1457        assert_eq!(held[0]["reason"], "5 of 6 failed");
1458
1459        let url = format!("{}/v1/user/operations/G/agents/007/hold", served.base);
1460        assert_eq!(
1461            call(reqwest::Method::DELETE, url.clone(), &served.viewer, None)
1462                .await
1463                .status(),
1464            StatusCode::FORBIDDEN
1465        );
1466        assert_eq!(
1467            call(
1468                reqwest::Method::DELETE,
1469                format!("{url}?model=opus"),
1470                &served.operator,
1471                None
1472            )
1473            .await
1474            .status(),
1475            StatusCode::BAD_REQUEST,
1476            "a route is named by its handler"
1477        );
1478        let lifted = call(reqwest::Method::DELETE, url.clone(), &served.operator, None).await;
1479        assert_eq!(lifted.status(), StatusCode::OK);
1480        let holds = served.registry.holds("G").unwrap();
1481        assert_eq!(holds.len(), 1, "the route's hold stays");
1482        assert_eq!(
1483            call(reqwest::Method::DELETE, url.clone(), &served.operator, None)
1484                .await
1485                .status(),
1486            StatusCode::NOT_FOUND
1487        );
1488        let route_url = format!("{url}?handler=claude&model=opus");
1489        assert_eq!(
1490            call(reqwest::Method::DELETE, route_url, &served.operator, None)
1491                .await
1492                .status(),
1493            StatusCode::OK
1494        );
1495        assert!(served.registry.holds("G").unwrap().is_empty());
1496        let actions: Vec<_> = served
1497            .registry
1498            .list_audit(20)
1499            .unwrap()
1500            .into_iter()
1501            .map(|record| record.action)
1502            .collect();
1503        assert_eq!(
1504            actions
1505                .iter()
1506                .filter(|action| *action == "agent.hold.lifted")
1507                .count(),
1508            2,
1509            "each lifting is audited first: {actions:?}"
1510        );
1511    }
1512}