1use serde_json::Value;
4
5use crate::traits::{MandateAuthority, ToolCallEffect, ToolCallSemantics};
6
7pub fn is_non_delegable_tool(tool_name: &str) -> bool {
11 MandateAuthority::NON_DELEGABLE_TOOLS.contains(&tool_name)
12}
13
14pub fn is_non_delegable(tool: &dyn aidaemon_tools::OutcomeTool) -> bool {
17 tool.dispatch_facts().opaque_execution || is_non_delegable_tool(tool.name())
18}
19
20const VERIFIER_STRATEGY_CHARS: usize = 2_000;
22
23pub fn verifier_request(mandate: &crate::traits::Mandate) -> String {
27 let strategy = mandate.strategy.as_ref().map(|strategy| {
28 serde_json::json!({
29 "description": strategy.description,
30 "body": aidaemon_events::text::truncate_str(&strategy.body, VERIFIER_STRATEGY_CHARS),
31 })
32 });
33 let statement = serde_json::json!({
34 "objective": mandate.objective,
35 "autonomy_mode": mandate.autonomy_mode,
36 "authority": mandate.authority,
37 "strategy": strategy,
38 "constraints": mandate.constraints,
39 "success_criteria": mandate.success_criteria,
40 "stop_conditions": mandate.stop_conditions,
41 });
42 format!(
43 "The owner confirmed this standing mandate (policy version {}). The assistant \
44 carries it out on its own over repeated reviews, so the owner does not ask for \
45 each action separately. An operation listed under authority, on a listed target, \
46 that serves the objective and respects the constraints is what the owner asked \
47 for; anything else is not. Mandate: {statement}",
48 mandate.version
49 )
50}
51
52pub fn bounded_owner_guidance(goal_context: Option<&str>) -> Vec<String> {
57 const MAX_ENTRIES: usize = 10;
58 const MAX_ENTRY_TEXT: usize = 1_024;
59 const MAX_TOTAL_TEXT: usize = 8 * 1_024;
60
61 let Some(entries) = goal_context
62 .and_then(|raw| serde_json::from_str::<Value>(raw).ok())
63 .and_then(|value| value.get("owner_guidance").cloned())
64 .and_then(|value| value.as_array().cloned())
65 else {
66 return Vec::new();
67 };
68
69 let mut newest_first = Vec::new();
70 let mut total_chars = 0usize;
71 let mut total_bytes = 0usize;
72 for entry in entries.iter().rev().take(MAX_ENTRIES) {
73 let Some(raw) = entry
74 .get("guidance")
75 .and_then(Value::as_str)
76 .map(str::trim)
77 .filter(|value| !value.is_empty())
78 else {
79 continue;
80 };
81 let remaining_chars = MAX_TOTAL_TEXT.saturating_sub(total_chars);
82 let remaining_bytes = MAX_TOTAL_TEXT.saturating_sub(total_bytes);
83 if remaining_chars == 0 || remaining_bytes == 0 {
84 break;
85 }
86 let max_chars = MAX_ENTRY_TEXT.min(remaining_chars);
87 let max_bytes = MAX_ENTRY_TEXT.min(remaining_bytes);
88 let mut guidance = String::new();
89 for character in raw.chars().take(max_chars) {
90 if guidance.len().saturating_add(character.len_utf8()) > max_bytes {
91 break;
92 }
93 guidance.push(character);
94 }
95 if guidance.is_empty() {
96 continue;
97 }
98 total_chars = total_chars.saturating_add(guidance.chars().count());
99 total_bytes = total_bytes.saturating_add(guidance.len());
100 newest_first.push(guidance);
101 }
102 newest_first.reverse();
103 newest_first
104}
105
106pub const DELIBERATOR_PROTOCOL_ACTIONS: &[(&str, MandateCallClass)] = &[
112 ("record_decision", MandateCallClass::RecordDecision),
113 ("record_measurement", MandateCallClass::RecordMeasurement),
114];
115
116pub fn deliberator_protocol_class(action: &str) -> Option<MandateCallClass> {
119 DELIBERATOR_PROTOCOL_ACTIONS
120 .iter()
121 .find(|(name, _)| *name == action)
122 .map(|(_, class)| *class)
123}
124
125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129pub enum MandateCallClass {
130 ProtocolObservation,
133 Observation,
136 RecordDecision,
138 RecordMeasurement,
141 ActControl,
144 GovernedMutation,
147 Deny,
149}
150
151pub fn classify_mandate_call(
152 tool_name: &str,
153 arguments: &str,
154 semantics: &ToolCallSemantics,
155) -> MandateCallClass {
156 let action = serde_json::from_str::<Value>(arguments)
157 .ok()
158 .and_then(|value| {
159 value
160 .get("action")
161 .and_then(Value::as_str)
162 .map(str::to_string)
163 });
164
165 if tool_name == crate::tools::mandate_review::MANDATE_REVIEW_TOOL {
166 return action
167 .as_deref()
168 .and_then(deliberator_protocol_class)
169 .unwrap_or(MandateCallClass::Deny);
170 }
171 if tool_name == "manage_mandates" {
174 return MandateCallClass::Deny;
175 }
176 if tool_name == "manage_goal_tasks" {
177 return match action.as_deref() {
178 Some("list_tasks") => MandateCallClass::ProtocolObservation,
179 Some("create_task" | "claim_task") => MandateCallClass::ActControl,
180 _ => MandateCallClass::Deny,
184 };
185 }
186 if tool_name == "spawn_agent" {
187 let synchronous = serde_json::from_str::<Value>(arguments)
192 .ok()
193 .and_then(|value| value.as_object().cloned())
194 .is_some_and(|object| {
195 object
196 .get("background")
197 .and_then(Value::as_bool)
198 .is_none_or(|background| !background)
199 });
200 return if synchronous {
201 MandateCallClass::ActControl
202 } else {
203 MandateCallClass::Deny
204 };
205 }
206 if tool_name == "report_blocker" {
207 return MandateCallClass::ActControl;
208 }
209 if is_non_delegable_tool(tool_name) {
213 return MandateCallClass::Deny;
214 }
215
216 if semantics.mutates_state()
217 || matches!(
218 semantics.effect,
219 ToolCallEffect::Mutation | ToolCallEffect::ObservationAndMutation
220 )
221 {
222 return MandateCallClass::GovernedMutation;
223 }
224 if semantics.effect == ToolCallEffect::Observation {
225 return MandateCallClass::Observation;
226 }
227 MandateCallClass::Deny
228}
229
230pub fn role_allows_mandate_call(
235 class: MandateCallClass,
236 tool_name: &str,
237 is_task_lead: bool,
238) -> bool {
239 if is_task_lead {
240 return match class {
241 MandateCallClass::ProtocolObservation
242 | MandateCallClass::Observation
243 | MandateCallClass::RecordDecision
244 | MandateCallClass::RecordMeasurement => true,
245 MandateCallClass::ActControl => {
246 matches!(tool_name, "manage_goal_tasks" | "spawn_agent")
247 }
248 MandateCallClass::GovernedMutation | MandateCallClass::Deny => false,
249 };
250 }
251
252 matches!(class, MandateCallClass::GovernedMutation)
253 || (class == MandateCallClass::ActControl && tool_name == "report_blocker")
254}
255
256pub fn mandate_denial_next_step(reason: &str, is_task_lead: bool) -> &'static str {
260 match reason {
261 "mandate_record_missing"
262 | "mandate_inactive"
263 | "mandate_expired"
264 | "mandate_execution_fence_lost"
265 | "mandate_run_missing"
266 | "invalid_mandate_run"
267 | "mandate_role_fence_missing"
268 | "mandate_worker_identity_mismatch"
269 | "mandate_version_mismatch"
270 | "invalid_mandate"
271 | "invalid_authority" => {
272 "This run can no longer act under the mandate and no retry will change that; \
273 stop calling tools and end with a short summary of what was done."
274 }
275 "mandate_task_lead_mutation_forbidden" => {
276 "A task lead never mutates: after a current ACT, create and claim the child task \
277 with manage_goal_tasks and spawn its executor with spawn_agent."
278 }
279 _ if !is_task_lead => {
280 "An executor only performs its granted mutation; it cannot observe or decide. \
281 Perform the mutation the task describes, or call report_blocker naming what is missing."
282 }
283 "act_decision_required" | "current_act_decision_required" | "decision_cycle_not_act" => {
284 "Record a current ACT with mandate_review record_decision before orchestrating, \
285 or record WAIT or ASK instead."
286 }
287 "cycle_budget_exhausted" | "invalid_cycle_budget" => {
288 "No mutation budget remains in this cycle; record WAIT with mandate_review."
289 }
290 "mandate_role_forbidden" => {
291 "This call is outside the task-lead protocol: observe, record the decision with \
292 mandate_review, or orchestrate the ACT's child task."
293 }
294 _ => {
295 "Choose a call inside the mandate's confirmed scopes, or record WAIT or ASK \
296 with mandate_review."
297 }
298 }
299}
300
301#[cfg(test)]
302mod tests {
303 use super::*;
304 use crate::traits::ToolMutationEffects;
305
306 #[test]
308 fn verifier_request_states_the_confirmed_policy() {
309 let mut mandate = crate::traits::Mandate::new(
310 "goal-synthetic",
311 None,
312 "Keep the Acme Corp account useful",
313 "telegram:synthetic-user-1",
314 MandateAuthority {
315 allowed_target_prefixes: vec!["https://api.example.invalid/posts".to_string()],
316 max_mutating_actions_per_cycle: 1,
317 ..Default::default()
318 },
319 900,
320 3600,
321 1800,
322 );
323 mandate.constraints = vec!["No engagement bait".to_string()];
324 mandate.strategy = Some(crate::traits::MandateStrategySnapshot {
325 skill_name: "voice".to_string(),
326 snapshot_version: 1,
327 content_sha256: String::new(),
328 description: "Plain factual voice".to_string(),
329 body: "b".repeat(9_000),
330 source: None,
331 });
332
333 let request = verifier_request(&mandate);
334
335 assert!(request.contains("The owner confirmed this standing mandate"));
336 assert!(request.contains("Keep the Acme Corp account useful"));
337 assert!(request.contains("https://api.example.invalid/posts"));
338 assert!(request.contains("No engagement bait"));
339 assert!(request.contains("Plain factual voice"));
340 assert!(!request.contains(&"b".repeat(2_001)), "the body is capped");
341 }
342
343 #[test]
344 fn mandate_denial_next_step_offers_only_what_the_role_can_do() {
345 let executor = mandate_denial_next_step("current_act_decision_required", false);
346 assert!(executor.contains("report_blocker"), "{executor}");
347 assert!(!executor.contains("record_decision"), "{executor}");
348
349 let lead = mandate_denial_next_step("current_act_decision_required", true);
350 assert!(lead.contains("record_decision"), "{lead}");
351 assert!(!lead.contains("report_blocker"), "{lead}");
352
353 let lead_mutation = mandate_denial_next_step("mandate_task_lead_mutation_forbidden", true);
354 assert!(lead_mutation.contains("spawn_agent"), "{lead_mutation}");
355
356 for terminal in ["mandate_execution_fence_lost", "mandate_inactive"] {
357 for is_task_lead in [true, false] {
358 let step = mandate_denial_next_step(terminal, is_task_lead);
359 assert!(step.contains("no retry"), "{terminal}: {step}");
360 }
361 }
362 }
363
364 #[test]
365 fn owner_guidance_extraction_ignores_unrelated_controller_context() {
366 let context = serde_json::json!({
367 "relevant_facts": [{"value": "private"}],
368 "recent_messages": ["unrelated history"],
369 "owner_guidance": [
370 {"guidance": "Prefer thoughtful replies", "recorded_at": "2026-01-01"}
371 ]
372 });
373 assert_eq!(
374 bounded_owner_guidance(Some(&context.to_string())),
375 vec!["Prefer thoughtful replies"]
376 );
377 }
378
379 #[test]
380 fn owner_guidance_extraction_enforces_entry_and_aggregate_bounds() {
381 let entries = (0..12)
382 .map(|index| {
383 serde_json::json!({
384 "guidance": format!("g{index:02}-{}", "x".repeat(1_100)),
385 "recorded_at": "2026-01-01"
386 })
387 })
388 .collect::<Vec<_>>();
389 let context = serde_json::json!({"owner_guidance": entries});
390 let guidance = bounded_owner_guidance(Some(&context.to_string()));
391 assert_eq!(
392 guidance.len(),
393 8,
394 "8 KiB total bound should admit eight 1,024-byte entries"
395 );
396 assert!(guidance.iter().all(|entry| entry.chars().count() == 1_024));
397 assert!(
398 guidance
399 .first()
400 .is_some_and(|entry| entry.starts_with("g04-"))
401 );
402 assert!(
403 guidance
404 .last()
405 .is_some_and(|entry| entry.starts_with("g11-"))
406 );
407 assert!(
408 guidance
409 .iter()
410 .map(|entry| entry.chars().count())
411 .sum::<usize>()
412 <= 8 * 1_024
413 );
414 assert!(guidance.iter().map(String::len).sum::<usize>() <= 8 * 1_024);
415 }
416
417 #[test]
418 fn owner_guidance_extraction_enforces_utf8_byte_bounds() {
419 let context = serde_json::json!({
420 "owner_guidance": [{"guidance": "🦀".repeat(2_000)}]
421 });
422 let guidance = bounded_owner_guidance(Some(&context.to_string()));
423 assert_eq!(guidance.len(), 1);
424 assert_eq!(guidance[0].len(), 1_024);
425 assert_eq!(guidance[0].chars().count(), 256);
426 }
427
428 #[test]
429 fn every_deliberator_protocol_action_is_reachable_by_the_task_lead_only() {
430 for (action, expected_class) in DELIBERATOR_PROTOCOL_ACTIONS {
431 let class = classify_mandate_call(
432 "mandate_review",
433 &format!(r#"{{"action":"{action}"}}"#),
434 &ToolCallSemantics::administrative(),
435 );
436 assert_eq!(class, *expected_class, "action {action}");
437 assert!(
438 role_allows_mandate_call(class, "mandate_review", true),
439 "task lead must be able to invoke deliberator protocol action {action}"
440 );
441 assert!(
442 !role_allows_mandate_call(class, "mandate_review", false),
443 "executors must not invoke deliberator protocol action {action}"
444 );
445 }
446 assert_eq!(
447 classify_mandate_call(
448 "mandate_review",
449 r#"{"action":"record_measurement"}"#,
450 &ToolCallSemantics::administrative(),
451 ),
452 MandateCallClass::RecordMeasurement
453 );
454 assert_eq!(
456 classify_mandate_call(
457 "manage_mandates",
458 r#"{"action":"record_decision"}"#,
459 &ToolCallSemantics::administrative(),
460 ),
461 MandateCallClass::Deny
462 );
463 }
464
465 #[test]
466 fn exact_control_calls_do_not_become_general_authority() {
467 assert_eq!(
468 classify_mandate_call(
469 "mandate_review",
470 r#"{"action":"record_decision"}"#,
471 &ToolCallSemantics::administrative(),
472 ),
473 MandateCallClass::RecordDecision
474 );
475 assert_eq!(
476 classify_mandate_call(
477 "manage_mandates",
478 r#"{"action":"update"}"#,
479 &ToolCallSemantics::administrative(),
480 ),
481 MandateCallClass::Deny
482 );
483 assert_eq!(
484 classify_mandate_call(
485 "manage_goal_tasks",
486 r#"{"action":"list_tasks"}"#,
487 &ToolCallSemantics::observation(),
488 ),
489 MandateCallClass::ProtocolObservation
490 );
491 assert_eq!(
492 classify_mandate_call(
493 "manage_goal_tasks",
494 r#"{"action":"complete_goal"}"#,
495 &ToolCallSemantics::mutation(),
496 ),
497 MandateCallClass::Deny
498 );
499 assert_eq!(
500 classify_mandate_call(
501 "manage_goal_tasks",
502 r#"{"action":"create_task"}"#,
503 &ToolCallSemantics::mutation(),
504 ),
505 MandateCallClass::ActControl
506 );
507 assert_eq!(
508 classify_mandate_call(
509 "manage_goal_tasks",
510 r#"{"action":"claim_task"}"#,
511 &ToolCallSemantics::mutation(),
512 ),
513 MandateCallClass::ActControl
514 );
515 for action in [
516 "update_task",
517 "retry_task",
518 "resolve_blocker",
519 "complete_goal",
520 "fail_goal",
521 ] {
522 assert_eq!(
523 classify_mandate_call(
524 "manage_goal_tasks",
525 &format!(r#"{{"action":"{action}"}}"#),
526 &ToolCallSemantics::mutation(),
527 ),
528 MandateCallClass::Deny,
529 "mandate task control action {action} must fail closed"
530 );
531 }
532 assert_eq!(
533 classify_mandate_call(
534 "http_request",
535 r#"{"method":"POST"}"#,
536 &ToolCallSemantics::mutation_with(ToolMutationEffects::REMOTE_MUTATION),
537 ),
538 MandateCallClass::GovernedMutation
539 );
540 assert_eq!(
541 classify_mandate_call(
542 "cli_agent",
543 r#"{"prompt":"do several things"}"#,
544 &ToolCallSemantics::mutation_with(ToolMutationEffects::UNSPECIFIED),
545 ),
546 MandateCallClass::Deny
547 );
548 assert_eq!(
549 classify_mandate_call(
550 "spawn_agent",
551 r#"{"mission":"run-bound","task":"exact task","background":false}"#,
552 &ToolCallSemantics::mutation(),
553 ),
554 MandateCallClass::ActControl
555 );
556 assert_eq!(
557 classify_mandate_call(
558 "spawn_agent",
559 r#"{"mission":"detached","task":"escape","background":true}"#,
560 &ToolCallSemantics::mutation(),
561 ),
562 MandateCallClass::Deny
563 );
564 for tool_name in [
565 "terminal",
566 "browser",
567 "computer_use",
568 "health_probe",
569 "manage_automations",
570 "schedule_task",
571 "read_file",
572 "write_file",
573 "edit_file",
574 "search_files",
575 "send_file",
576 "check_environment",
577 ] {
578 assert_eq!(
579 classify_mandate_call(
580 tool_name,
581 r#"{"url":"https://api.x.com/2/tweets"}"#,
582 &ToolCallSemantics::observation(),
583 ),
584 MandateCallClass::Deny,
585 "opaque adapter {tool_name} must fail closed even as an observation"
586 );
587 }
588 }
589
590 #[test]
591 fn mandate_roles_are_fail_closed_at_dispatch() {
592 assert!(role_allows_mandate_call(
593 MandateCallClass::RecordDecision,
594 "mandate_review",
595 true,
596 ));
597 assert!(role_allows_mandate_call(
598 MandateCallClass::ActControl,
599 "manage_goal_tasks",
600 true,
601 ));
602 assert!(role_allows_mandate_call(
603 MandateCallClass::ActControl,
604 "spawn_agent",
605 true,
606 ));
607 assert!(!role_allows_mandate_call(
608 MandateCallClass::GovernedMutation,
609 "http_request",
610 true,
611 ));
612 assert!(!role_allows_mandate_call(
613 MandateCallClass::ActControl,
614 "report_blocker",
615 true,
616 ));
617
618 assert!(role_allows_mandate_call(
619 MandateCallClass::GovernedMutation,
620 "http_request",
621 false,
622 ));
623 assert!(role_allows_mandate_call(
624 MandateCallClass::ActControl,
625 "report_blocker",
626 false,
627 ));
628 for (class, tool) in [
629 (MandateCallClass::RecordDecision, "mandate_review"),
630 (MandateCallClass::ProtocolObservation, "manage_goal_tasks"),
631 (MandateCallClass::Observation, "web_fetch"),
632 (MandateCallClass::ActControl, "manage_goal_tasks"),
633 (MandateCallClass::ActControl, "spawn_agent"),
634 ] {
635 assert!(
636 !role_allows_mandate_call(class, tool, false),
637 "executor unexpectedly received task-lead authority for {tool}"
638 );
639 }
640 }
641}