Skip to main content

adk_kernel/agents/
record.rs

1//! An agent a person adds: its definition and the record the kernel keeps (spec 3.3 §5.7).
2
3use std::fmt;
4
5use adk_core::principal::SubjectRef;
6use adk_core::{AdkError, AgentId, AgentPrincipal, ErrorCategory, ErrorComponent};
7use chrono::{DateTime, Utc};
8use serde::{Deserialize, Serialize};
9
10use crate::error::{AGENT_INVALID_CODE, KernelError, Result};
11use crate::partition::{Partition, PartitionId, PartitionMode};
12
13/// The longest id the kernel gives an agent.
14pub const MAX_AGENT_ID_LEN: usize = 40;
15/// The longest name an agent may have, in characters (spec 3.3 §5.7).
16pub const MAX_AGENT_NAME_LEN: usize = 40;
17/// The longest "What it does" line, in characters.
18pub const MAX_AGENT_DESCRIPTION_LEN: usize = 200;
19/// The longest instructions an agent may have, in characters.
20pub const MAX_AGENT_INSTRUCTIONS_LEN: usize = 16_000;
21/// The id an agent gets when its name has no letter or digit (spec 3.3 §5.7).
22pub const FALLBACK_AGENT_ID: &str = "agent";
23/// Ids no added agent ever gets, beside any containing `@` or `.` and the host's own
24/// targets (spec 3.3 §5.7).
25pub const RESERVED_AGENT_IDS: [&str; 2] = ["adk-rust", "self-improver"];
26/// The name no added agent may take beside the primary agent's (spec 3.3 §5.7).
27pub const RESERVED_AGENT_NAME: &str = "You";
28
29/// Whether `c` is a format character that draws nothing (Unicode category Cf): the soft
30/// hyphen, zero-width spaces and joiners, direction marks and isolates, the word joiner, the
31/// byte order mark and tag characters.
32fn invisible(c: char) -> bool {
33    matches!(
34        c,
35        '\u{ad}'
36            | '\u{600}'..='\u{605}'
37            | '\u{61c}'
38            | '\u{6dd}'
39            | '\u{70f}'
40            | '\u{180e}'
41            | '\u{200b}'..='\u{200f}'
42            | '\u{202a}'..='\u{202e}'
43            | '\u{2060}'..='\u{2064}'
44            | '\u{2066}'..='\u{206f}'
45            | '\u{feff}'
46            | '\u{fff9}'..='\u{fffb}'
47            | '\u{e0001}'
48            | '\u{e0020}'..='\u{e007f}'
49    )
50}
51
52fn invalid(reason: impl Into<String>) -> KernelError {
53    KernelError::Core(AdkError::new(
54        ErrorComponent::Server,
55        ErrorCategory::InvalidInput,
56        AGENT_INVALID_CODE,
57        reason.into(),
58    ))
59}
60
61/// One of the eight avatar colours the surfaces draw an agent's monogram in (spec 3.3 §5.7,
62/// §9), in the order of `adk-surface`'s avatar palette. The kernel keeps the name, never a
63/// colour value.
64///
65/// # Example
66///
67/// ```rust
68/// use adk_kernel::agents::AvatarColor;
69///
70/// assert_eq!(AvatarColor::ALL.len(), 8);
71/// assert_eq!(serde_json::to_value(AvatarColor::Teal).unwrap(), "teal");
72/// assert_eq!(AvatarColor::for_name("Finance"), AvatarColor::for_name("Finance"));
73/// ```
74#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
75#[serde(rename_all = "camelCase")]
76pub enum AvatarColor {
77    /// The first colour of the palette.
78    #[default]
79    Orange,
80    /// The second.
81    Green,
82    /// The third.
83    Blue,
84    /// The fourth.
85    Violet,
86    /// The fifth.
87    Slate,
88    /// The sixth.
89    Amber,
90    /// The seventh.
91    Teal,
92    /// The eighth.
93    Pink,
94}
95
96impl AvatarColor {
97    /// Every colour, in palette order.
98    pub const ALL: [Self; 8] = [
99        Self::Orange,
100        Self::Green,
101        Self::Blue,
102        Self::Violet,
103        Self::Slate,
104        Self::Amber,
105        Self::Teal,
106        Self::Pink,
107    ];
108
109    /// The colour's position in the palette, 0 to 7.
110    pub fn index(self) -> usize {
111        match self {
112            Self::Orange => 0,
113            Self::Green => 1,
114            Self::Blue => 2,
115            Self::Violet => 3,
116            Self::Slate => 4,
117            Self::Amber => 5,
118            Self::Teal => 6,
119            Self::Pink => 7,
120        }
121    }
122
123    /// The colour the surfaces draw `display_name` in when nothing chose one: the FNV-1a hash
124    /// of its bytes over the palette, as `adk-surface` picks an avatar colour.
125    pub fn for_name(display_name: &str) -> Self {
126        let hash = display_name.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
127            (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
128        });
129        Self::ALL[(hash % Self::ALL.len() as u64) as usize]
130    }
131
132    /// The colour's name.
133    pub fn as_str(self) -> &'static str {
134        match self {
135            Self::Orange => "orange",
136            Self::Green => "green",
137            Self::Blue => "blue",
138            Self::Violet => "violet",
139            Self::Slate => "slate",
140            Self::Amber => "amber",
141            Self::Teal => "teal",
142            Self::Pink => "pink",
143        }
144    }
145}
146
147impl fmt::Display for AvatarColor {
148    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149        f.pad(self.as_str())
150    }
151}
152
153impl std::str::FromStr for AvatarColor {
154    type Err = KernelError;
155
156    fn from_str(text: &str) -> Result<Self> {
157        let text = text.trim().to_ascii_lowercase();
158        Self::ALL.into_iter().find(|color| color.as_str() == text).ok_or_else(|| {
159            invalid(format!(
160                "unknown colour `{text}`; use one of {}",
161                Self::ALL.map(Self::as_str).join(", ")
162            ))
163        })
164    }
165}
166
167/// The provider and model an agent runs on (spec 3.3 §5.7, decision 21). Never a key: keys
168/// stay in the kernel's environment.
169///
170/// # Example
171///
172/// ```rust
173/// use adk_kernel::agents::ModelChoice;
174///
175/// let model = ModelChoice::new("anthropic", "claude-sonnet-5-5");
176/// assert_eq!(serde_json::to_value(&model).unwrap()["provider"], "anthropic");
177/// assert!(model.validate().is_ok());
178/// assert!(ModelChoice::new("anthropic", "sk-ant key").validate().is_err());
179/// ```
180#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
181#[serde(rename_all = "camelCase", deny_unknown_fields)]
182#[non_exhaustive]
183pub struct ModelChoice {
184    /// The provider: `anthropic`, `openai`, `gemini`, …
185    pub provider: String,
186    /// The model id, such as `claude-sonnet-5-5`.
187    pub model: String,
188}
189
190impl ModelChoice {
191    /// The model `model` of `provider`.
192    pub fn new(provider: impl Into<String>, model: impl Into<String>) -> Self {
193        Self { provider: provider.into(), model: model.into() }
194    }
195
196    /// Checks both are short identifiers: non-empty, at most 100 characters, without
197    /// whitespace or control characters.
198    ///
199    /// # Errors
200    ///
201    /// Returns a `kernel.agent.invalid` error naming the field.
202    pub fn validate(&self) -> Result<()> {
203        for (field, value) in [("provider", &self.provider), ("model", &self.model)] {
204            if value.is_empty()
205                || value.chars().count() > 100
206                || value.chars().any(|c| c.is_whitespace() || c.is_control())
207            {
208                return Err(invalid(format!(
209                    "the model's {field} must be a name of at most 100 characters without \
210                     spaces, such as `claude-sonnet-5-5`; keys are never part of an agent"
211                )));
212            }
213        }
214        Ok(())
215    }
216}
217
218/// What an agent may do with files in its area's workspace (spec 3.3 §5.7).
219///
220/// # Example
221///
222/// ```rust
223/// use adk_kernel::agents::FileAccess;
224///
225/// assert!(FileAccess::Read < FileAccess::ReadWrite);
226/// assert_eq!(serde_json::to_value(FileAccess::ReadWrite).unwrap(), "readWrite");
227/// ```
228#[derive(
229    Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize,
230)]
231#[serde(rename_all = "camelCase")]
232pub enum FileAccess {
233    /// No files.
234    #[default]
235    None,
236    /// Read files.
237    Read,
238    /// Read and change files.
239    ReadWrite,
240}
241
242/// Whether an agent has a shell (spec 3.3 §5.7).
243///
244/// # Example
245///
246/// ```rust
247/// use adk_kernel::agents::ShellAccess;
248///
249/// assert!(ShellAccess::Sandboxed < ShellAccess::Host);
250/// assert_eq!(serde_json::to_value(ShellAccess::Host).unwrap(), "host");
251/// ```
252#[derive(
253    Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize,
254)]
255#[serde(rename_all = "camelCase")]
256pub enum ShellAccess {
257    /// No shell.
258    #[default]
259    None,
260    /// A shell in the sandbox.
261    Sandboxed,
262    /// A shell on this computer.
263    Host,
264}
265
266/// Which sites an agent may reach (spec 3.3 §5.7).
267///
268/// # Example
269///
270/// ```rust
271/// use adk_kernel::agents::WebAccess;
272///
273/// let listed = WebAccess::listed(["Example.com", "docs.rs", "example.com"]);
274/// assert_eq!(listed, WebAccess::Listed { hosts: vec!["docs.rs".into(), "example.com".into()] });
275/// assert_eq!(serde_json::to_value(&listed).unwrap()["access"], "listed");
276/// assert!(WebAccess::None.within(&listed) && listed.within(&WebAccess::Any));
277/// ```
278#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
279#[serde(tag = "access", rename_all = "camelCase", rename_all_fields = "camelCase")]
280pub enum WebAccess {
281    /// No site.
282    #[default]
283    None,
284    /// Only these hosts.
285    Listed {
286        /// The hosts, lowercase, sorted and unique.
287        hosts: Vec<String>,
288    },
289    /// Any site.
290    Any,
291}
292
293impl WebAccess {
294    /// The hosts `hosts`, lowercased, sorted and unique.
295    pub fn listed(hosts: impl IntoIterator<Item = impl Into<String>>) -> Self {
296        let mut hosts: Vec<String> =
297            hosts.into_iter().map(|host| host.into().trim().to_ascii_lowercase()).collect();
298        hosts.sort();
299        hosts.dedup();
300        Self::Listed { hosts }
301    }
302
303    /// How much it opens: 0 for none, 1 for listed hosts, 2 for any site.
304    pub fn reach(&self) -> u8 {
305        match self {
306            Self::None => 0,
307            Self::Listed { .. } => 1,
308            Self::Any => 2,
309        }
310    }
311
312    /// Whether every site `self` reaches, `ceiling` reaches too.
313    pub fn within(&self, ceiling: &Self) -> bool {
314        match (self, ceiling) {
315            (Self::None, _) | (_, Self::Any) => true,
316            (Self::Listed { hosts }, Self::Listed { hosts: allowed }) => {
317                hosts.iter().all(|host| allowed.contains(host))
318            }
319            (Self::Listed { .. } | Self::Any, Self::None | Self::Listed { .. }) => false,
320        }
321    }
322
323    fn normalized(self) -> Self {
324        match self {
325            Self::Listed { hosts } => Self::listed(hosts),
326            other => other,
327        }
328    }
329}
330
331/// What an agent can use (spec 3.3 §5.7): files in its area's workspace or one folder
332/// inside it, a shell, the web, packs, and drivers mounted for its area. Adding an agent
333/// never mounts a driver (K-I13).
334///
335/// # Example
336///
337/// ```rust
338/// use adk_kernel::agents::{AgentUses, FileAccess, WebAccess};
339///
340/// let uses = AgentUses::default()
341///     .with_files(FileAccess::Read)
342///     .with_folder("Invoices")
343///     .with_web(WebAccess::listed(["example.com"]));
344/// let wire = serde_json::to_value(&uses).unwrap();
345/// assert_eq!(wire["files"], "read");
346/// assert_eq!(wire["folder"], "Invoices");
347/// assert_eq!(wire["shell"], "none");
348/// assert_eq!(serde_json::from_value::<AgentUses>(wire).unwrap(), uses);
349/// ```
350#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
351#[serde(rename_all = "camelCase", deny_unknown_fields)]
352#[non_exhaustive]
353pub struct AgentUses {
354    /// Files in the area's workspace, or in [`folder`](Self::folder).
355    #[serde(default)]
356    pub files: FileAccess,
357    /// One folder inside the area's workspace, relative to it; `None` for the whole
358    /// workspace.
359    #[serde(default, skip_serializing_if = "Option::is_none")]
360    pub folder: Option<String>,
361    /// A shell.
362    #[serde(default)]
363    pub shell: ShellAccess,
364    /// The web.
365    #[serde(default)]
366    pub web: WebAccess,
367    /// The packs it has, by name, sorted and unique.
368    #[serde(default, skip_serializing_if = "Vec::is_empty")]
369    pub packs: Vec<String>,
370    /// The drivers it uses, by id, each mounted for its area, sorted and unique.
371    #[serde(default, skip_serializing_if = "Vec::is_empty")]
372    pub drivers: Vec<String>,
373}
374
375impl AgentUses {
376    /// Sets file access.
377    #[must_use]
378    pub fn with_files(mut self, files: FileAccess) -> Self {
379        self.files = files;
380        self
381    }
382
383    /// Narrows files to `folder`, relative to the area's workspace.
384    #[must_use]
385    pub fn with_folder(mut self, folder: impl Into<String>) -> Self {
386        self.folder = Some(folder.into());
387        self
388    }
389
390    /// Sets the shell.
391    #[must_use]
392    pub fn with_shell(mut self, shell: ShellAccess) -> Self {
393        self.shell = shell;
394        self
395    }
396
397    /// Sets the web.
398    #[must_use]
399    pub fn with_web(mut self, web: WebAccess) -> Self {
400        self.web = web;
401        self
402    }
403
404    /// Adds a pack.
405    #[must_use]
406    pub fn with_pack(mut self, pack: impl Into<String>) -> Self {
407        self.packs.push(pack.into());
408        self
409    }
410
411    /// Adds a driver.
412    #[must_use]
413    pub fn with_driver(mut self, driver: impl Into<String>) -> Self {
414        self.drivers.push(driver.into());
415        self
416    }
417
418    /// The same uses with packs, drivers and hosts sorted and unique, and the folder in its
419    /// canonical form (`/` separators, no `.` parts, no trailing `/`).
420    #[must_use]
421    pub fn normalized(mut self) -> Self {
422        for list in [&mut self.packs, &mut self.drivers] {
423            for item in list.iter_mut() {
424                *item = item.trim().to_string();
425            }
426            list.sort();
427            list.dedup();
428        }
429        self.web = self.web.normalized();
430        self.folder = self.folder.and_then(|folder| {
431            let parts: Vec<&str> =
432                folder.split(['/', '\\']).filter(|part| !part.is_empty() && *part != ".").collect();
433            (!parts.is_empty()).then(|| parts.join("/"))
434        });
435        self
436    }
437
438    /// Whether `self` allows nothing `ceiling` does not, dimension by dimension; the names of
439    /// the dimensions over it otherwise, in plain words.
440    ///
441    /// # Example
442    ///
443    /// ```rust
444    /// use adk_kernel::agents::{AgentUses, FileAccess, ShellAccess};
445    ///
446    /// let suggester = AgentUses::default().with_files(FileAccess::ReadWrite).with_folder("Docs");
447    /// let ok = AgentUses::default().with_files(FileAccess::Read).with_folder("Docs/Invoices");
448    /// assert!(ok.over(&suggester).is_empty());
449    /// let over = AgentUses::default()
450    ///     .with_files(FileAccess::Read)
451    ///     .with_folder("Mail")
452    ///     .with_shell(ShellAccess::Sandboxed);
453    /// assert_eq!(over.over(&suggester), ["the folder Mail", "a shell in the sandbox"]);
454    /// ```
455    pub fn over(&self, ceiling: &Self) -> Vec<String> {
456        let mine = self.clone().normalized();
457        let ceiling = ceiling.clone().normalized();
458        let mut over = Vec::new();
459        if mine.files > ceiling.files {
460            over.push(
461                match mine.files {
462                    FileAccess::ReadWrite => "changing files",
463                    _ => "reading files",
464                }
465                .to_string(),
466            );
467        }
468        if mine.files != FileAccess::None
469            && let Some(allowed) = &ceiling.folder
470        {
471            let inside = mine.folder.as_ref().is_some_and(|folder| {
472                folder == allowed || folder.starts_with(&format!("{allowed}/"))
473            });
474            if !inside {
475                over.push(match &mine.folder {
476                    Some(folder) => format!("the folder {folder}"),
477                    None => "files outside the folder it may use".to_string(),
478                });
479            }
480        }
481        if mine.shell > ceiling.shell {
482            over.push(
483                match mine.shell {
484                    ShellAccess::Host => "a shell on this computer",
485                    _ => "a shell in the sandbox",
486                }
487                .to_string(),
488            );
489        }
490        if !mine.web.within(&ceiling.web) {
491            over.push(match &mine.web {
492                WebAccess::Any => "any site".to_string(),
493                WebAccess::Listed { hosts } => {
494                    let extra: Vec<&str> = hosts
495                        .iter()
496                        .filter(|host| match &ceiling.web {
497                            WebAccess::Listed { hosts: allowed } => !allowed.contains(host),
498                            _ => true,
499                        })
500                        .map(String::as_str)
501                        .collect();
502                    format!("the sites {}", extra.join(", "))
503                }
504                WebAccess::None => String::new(),
505            });
506        }
507        for pack in mine.packs.iter().filter(|pack| !ceiling.packs.contains(pack)) {
508            over.push(format!("the {pack} pack"));
509        }
510        for driver in mine.drivers.iter().filter(|driver| !ceiling.drivers.contains(driver)) {
511            over.push(format!("the {driver} driver"));
512        }
513        over
514    }
515
516    fn validate(&self) -> Result<()> {
517        if let Some(folder) = &self.folder {
518            let absolute = folder.starts_with('/')
519                || folder.starts_with('\\')
520                || folder.starts_with('~')
521                || folder.as_bytes().get(1) == Some(&b':')
522                || std::path::Path::new(folder).is_absolute();
523            if absolute
524                || folder.split(['/', '\\']).any(|part| part == "..")
525                || folder.chars().any(char::is_control)
526            {
527                return Err(invalid(format!(
528                    "the folder `{folder}` must be a folder inside the area's workspace, \
529                     written relative to it without `..`, such as `Invoices`"
530                )));
531            }
532        }
533        if let WebAccess::Listed { hosts } = &self.web {
534            if hosts.is_empty() {
535                return Err(invalid(
536                    "listed sites need at least one host; use no web access instead",
537                ));
538            }
539            for host in hosts {
540                let valid = !host.is_empty()
541                    && host.len() <= 253
542                    && host.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-'))
543                    && !host.starts_with(['.', '-'])
544                    && !host.ends_with(['.', '-']);
545                if !valid {
546                    return Err(invalid(format!(
547                        "`{host}` is not a host name; list sites as `example.com`, without a \
548                         scheme or a path"
549                    )));
550                }
551            }
552        }
553        for (what, list) in [("pack", &self.packs), ("driver", &self.drivers)] {
554            if let Some(bad) = list.iter().find(|item| {
555                item.trim().is_empty() || item.len() > 100 || item.chars().any(char::is_control)
556            }) {
557                return Err(invalid(format!("`{bad}` is not a {what} name")));
558            }
559        }
560        Ok(())
561    }
562}
563
564/// Where an agent is in its life (spec 3.3 §5.7). Never named `AgentState` or
565/// `AgentStatus`, which `adk-surface` uses for a roster row.
566///
567/// # Example
568///
569/// ```rust
570/// use adk_kernel::agents::AgentRecordState;
571///
572/// assert_eq!(serde_json::to_value(AgentRecordState::Proposed).unwrap(), "proposed");
573/// assert!(AgentRecordState::Paused.holds_its_name());
574/// assert!(!AgentRecordState::Removed.holds_its_name());
575/// ```
576#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
577#[serde(rename_all = "camelCase")]
578pub enum AgentRecordState {
579    /// Another agent suggested it; it waits for a person in the inbox.
580    Proposed,
581    /// Added; the kernel hosts it.
582    Active,
583    /// Paused by a person: its processes are suspended and it is not given new work.
584    Paused,
585    /// Being removed; the next tick on any replica finishes the removal.
586    Removing,
587    /// Removed: a tombstone, so its id is never given again (S-I14).
588    Removed,
589    /// A suggestion that ended refused, such as over its suggester's limits at approval.
590    Refused,
591}
592
593impl AgentRecordState {
594    /// The state's name.
595    pub fn as_str(self) -> &'static str {
596        match self {
597            Self::Proposed => "proposed",
598            Self::Active => "active",
599            Self::Paused => "paused",
600            Self::Removing => "removing",
601            Self::Removed => "removed",
602            Self::Refused => "refused",
603        }
604    }
605
606    /// Whether an agent in this state keeps its name from every other agent: active, paused
607    /// and suggested agents do (spec 3.3 §5.7).
608    pub fn holds_its_name(self) -> bool {
609        matches!(self, Self::Proposed | Self::Active | Self::Paused)
610    }
611
612    /// Whether the kernel hosts an agent in this state: active and paused agents, so a
613    /// paused agent's parked work stays resumable.
614    pub fn is_hosted(self) -> bool {
615        matches!(self, Self::Active | Self::Paused)
616    }
617}
618
619impl fmt::Display for AgentRecordState {
620    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
621        f.pad(self.as_str())
622    }
623}
624
625/// How an agent was added (spec 3.3 §5.7).
626///
627/// # Example
628///
629/// ```rust
630/// use adk_core::AgentId;
631/// use adk_kernel::agents::AgentOrigin;
632///
633/// let origin = AgentOrigin::Suggested {
634///     agent: AgentId::new("urn:adk:agent:adk-rust/adk-rust").unwrap(),
635///     session: "s-1".into(),
636///     run: None,
637///     unattended: false,
638/// };
639/// let wire = serde_json::to_value(&origin).unwrap();
640/// assert_eq!(wire["kind"], "suggested");
641/// assert_eq!(serde_json::to_value(AgentOrigin::ByHand).unwrap()["kind"], "byHand");
642/// ```
643#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
644#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")]
645pub enum AgentOrigin {
646    /// A person set it up in the web home or the terminal.
647    ByHand,
648    /// An agent suggested it and a person approved the suggestion.
649    Suggested {
650        /// The suggesting agent.
651        agent: AgentId,
652        /// The session it was suggested in.
653        session: String,
654        /// The durable run that suggested it, when one did.
655        #[serde(default, skip_serializing_if = "Option::is_none")]
656        run: Option<String>,
657        /// Whether it was suggested during work the person did not start at a screen: a
658        /// process that is not interactive, or a turn that came from a chat message. Such a
659        /// suggestion is high risk (decision 20).
660        #[serde(default)]
661        unattended: bool,
662    },
663}
664
665/// What a person defines when they add an agent (spec 3.3 §5.7): every field a decision
666/// shows and the digest binds, and nothing the kernel keeps about its life.
667///
668/// # Example
669///
670/// ```rust
671/// use adk_kernel::agents::{AgentDefinition, AgentUses, FileAccess};
672/// use adk_kernel::PartitionMode;
673///
674/// let finance = AgentDefinition::new("Finance", "default")
675///     .with_description("Reads invoices and drafts payment reminders")
676///     .with_instructions("Draft reminders; never send them.")
677///     .with_mode(PartitionMode::Ask)
678///     .with_uses(AgentUses::default().with_files(FileAccess::Read).with_folder("Invoices"));
679/// assert!(finance.validate().is_ok());
680/// assert_eq!(finance.digest(), finance.clone().digest());
681/// assert_ne!(finance.digest(), finance.clone().with_mode(PartitionMode::Plan).digest());
682/// ```
683#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
684#[serde(rename_all = "camelCase", deny_unknown_fields)]
685#[non_exhaustive]
686pub struct AgentDefinition {
687    /// The name on screen, such as "Finance".
688    pub display_name: String,
689    /// The avatar colour, kept across a rename.
690    pub color: AvatarColor,
691    /// What it does, one line.
692    #[serde(default)]
693    pub description: String,
694    /// How it works. Instructions shape what it says and tries, never what it may do.
695    #[serde(default)]
696    pub instructions: String,
697    /// Its area; fixed once it is added.
698    pub area: PartitionId,
699    /// How much it asks first: its area's mode or stricter.
700    pub mode: PartitionMode,
701    /// The model it runs on; `None` for the primary agent's.
702    #[serde(default, skip_serializing_if = "Option::is_none")]
703    pub model: Option<ModelChoice>,
704    /// What it can use.
705    #[serde(default)]
706    pub uses: AgentUses,
707    /// Its daily spending limit in micro-USD; at most its area's.
708    #[serde(default, skip_serializing_if = "Option::is_none")]
709    pub daily_limit_micro_usd: Option<u64>,
710}
711
712impl AgentDefinition {
713    /// An agent named `display_name` in `area`, in its name's colour, in `ask` mode, using
714    /// nothing.
715    pub fn new(display_name: impl Into<String>, area: impl Into<PartitionId>) -> Self {
716        let display_name = display_name.into();
717        Self {
718            color: AvatarColor::for_name(display_name.trim()),
719            display_name,
720            description: String::new(),
721            instructions: String::new(),
722            area: area.into(),
723            mode: PartitionMode::Ask,
724            model: None,
725            uses: AgentUses::default(),
726            daily_limit_micro_usd: None,
727        }
728    }
729
730    /// Sets the colour.
731    #[must_use]
732    pub fn with_color(mut self, color: AvatarColor) -> Self {
733        self.color = color;
734        self
735    }
736
737    /// Sets what it does.
738    #[must_use]
739    pub fn with_description(mut self, description: impl Into<String>) -> Self {
740        self.description = description.into();
741        self
742    }
743
744    /// Sets the instructions.
745    #[must_use]
746    pub fn with_instructions(mut self, instructions: impl Into<String>) -> Self {
747        self.instructions = instructions.into();
748        self
749    }
750
751    /// Sets how much it asks first.
752    #[must_use]
753    pub fn with_mode(mut self, mode: PartitionMode) -> Self {
754        self.mode = mode;
755        self
756    }
757
758    /// Sets the model.
759    #[must_use]
760    pub fn with_model(mut self, model: ModelChoice) -> Self {
761        self.model = Some(model);
762        self
763    }
764
765    /// Sets what it can use.
766    #[must_use]
767    pub fn with_uses(mut self, uses: AgentUses) -> Self {
768        self.uses = uses;
769        self
770    }
771
772    /// Sets the daily spending limit.
773    #[must_use]
774    pub fn with_daily_limit(mut self, micro_usd: u64) -> Self {
775        self.daily_limit_micro_usd = Some(micro_usd);
776        self
777    }
778
779    /// The definition in canonical form: the name and line trimmed, the uses
780    /// [normalized](AgentUses::normalized). Two definitions that differ only in form have
781    /// one digest.
782    #[must_use]
783    pub fn normalized(mut self) -> Self {
784        self.display_name = self.display_name.trim().to_string();
785        self.description = self.description.trim().to_string();
786        self.uses = self.uses.normalized();
787        self
788    }
789
790    /// Checks the rules every definition keeps on its own (spec 3.3 §5.7): a name of 1 to
791    /// [`MAX_AGENT_NAME_LEN`] characters that is not "You"; one line of what it does; at
792    /// most [`MAX_AGENT_INSTRUCTIONS_LEN`] characters of instructions; an area; a model
793    /// name, not a key; a folder inside the workspace, without `..`; host names; a limit
794    /// above zero. The rules that need the kernel — names taken, the area's limits — are the
795    /// agent table's.
796    ///
797    /// # Errors
798    ///
799    /// Returns a `kernel.agent.invalid` error saying which rule the definition breaks.
800    pub fn validate(&self) -> Result<()> {
801        let name = self.display_name.trim();
802        let length = name.chars().count();
803        if length == 0 || length > MAX_AGENT_NAME_LEN || name.chars().any(char::is_control) {
804            return Err(invalid(format!(
805                "an agent's name is 1 to {MAX_AGENT_NAME_LEN} characters on one line"
806            )));
807        }
808        // An invisible character would let a name read as the primary agent's or another
809        // agent's while comparing unequal (spec 3.3 §5.7, S-I14).
810        if name.chars().any(invisible) {
811            return Err(invalid(
812                "an agent's name may not hold invisible characters, such as zero-width spaces \
813                 or direction marks",
814            ));
815        }
816        if name.eq_ignore_ascii_case(RESERVED_AGENT_NAME) {
817            return Err(invalid(format!("\"{name}\" is reserved; choose another name")));
818        }
819        let description = self.description.trim();
820        if description.chars().count() > MAX_AGENT_DESCRIPTION_LEN
821            || description.chars().any(|c| c.is_control() || invisible(c))
822        {
823            return Err(invalid(format!(
824                "\"What it does\" is one line of at most {MAX_AGENT_DESCRIPTION_LEN} characters"
825            )));
826        }
827        if self.instructions.chars().count() > MAX_AGENT_INSTRUCTIONS_LEN {
828            return Err(invalid(format!(
829                "instructions are at most {MAX_AGENT_INSTRUCTIONS_LEN} characters; shorten them"
830            )));
831        }
832        if self.instructions.chars().any(|c| c.is_control() && !matches!(c, '\n' | '\t' | '\r')) {
833            return Err(invalid("instructions may not hold control characters"));
834        }
835        if self.area.as_str().trim().is_empty() || self.area.as_str().chars().any(char::is_control)
836        {
837            return Err(invalid("an agent needs an area"));
838        }
839        if let Some(model) = &self.model {
840            model.validate()?;
841        }
842        if self.daily_limit_micro_usd == Some(0) {
843            return Err(invalid(
844                "a daily spending limit is above zero; leave it out for the area's limit",
845            ));
846        }
847        self.uses.validate()
848    }
849
850    /// The digest a decision binds to: the SHA-256, in lowercase hex, of the canonical JSON
851    /// of the [normalized](Self::normalized) definition (spec 3.3 §5.7). It covers every
852    /// definition field and nothing else: not the state, version, timestamps or origin.
853    pub fn digest(&self) -> String {
854        use sha2::Digest as _;
855
856        let canonical = serde_json::to_vec(&self.clone().normalized()).unwrap_or_default();
857        sha2::Sha256::digest(&canonical).iter().map(|byte| format!("{byte:02x}")).collect()
858    }
859}
860
861/// An agent the kernel keeps (spec 3.3 §5.7, §10 K7): its definition, beside its id, state,
862/// how it was added, who added and approved it, when, a version per change and the digest of
863/// its definition.
864///
865/// # Example
866///
867/// ```rust
868/// use adk_core::principal::SubjectRef;
869/// use adk_kernel::agents::{AgentDefinition, AgentOrigin, AgentRecord, AgentRecordState};
870///
871/// let record = AgentRecord::new(
872///     "finance",
873///     AgentDefinition::new("Finance", "default"),
874///     AgentRecordState::Active,
875///     AgentOrigin::ByHand,
876///     SubjectRef::human("alice"),
877///     chrono::Utc::now(),
878/// );
879/// assert_eq!(record.version, 1);
880/// assert_eq!(record.digest, record.definition().digest());
881/// assert!(record.validate().is_ok());
882/// let wire = serde_json::to_value(&record).unwrap();
883/// assert_eq!(wire["displayName"], "Finance");
884/// assert_eq!(serde_json::from_value::<AgentRecord>(wire).unwrap(), record);
885/// ```
886#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
887#[serde(rename_all = "camelCase", deny_unknown_fields)]
888#[non_exhaustive]
889pub struct AgentRecord {
890    /// The id, given once from its first name: its kernel target, its root agent name and
891    /// the last part of its identity, `urn:adk:agent:{app}/{id}`.
892    pub id: String,
893    /// The name on screen.
894    pub display_name: String,
895    /// The avatar colour.
896    pub color: AvatarColor,
897    /// What it does, one line.
898    #[serde(default)]
899    pub description: String,
900    /// How it works.
901    #[serde(default)]
902    pub instructions: String,
903    /// Its area.
904    pub area: PartitionId,
905    /// How much it asks first.
906    pub mode: PartitionMode,
907    /// The model it runs on; `None` for the primary agent's.
908    #[serde(default, skip_serializing_if = "Option::is_none")]
909    pub model: Option<ModelChoice>,
910    /// What it can use.
911    #[serde(default)]
912    pub uses: AgentUses,
913    /// Its daily spending limit in micro-USD.
914    #[serde(default, skip_serializing_if = "Option::is_none")]
915    pub daily_limit_micro_usd: Option<u64>,
916    /// Where it is in its life.
917    pub state: AgentRecordState,
918    /// How it was added.
919    pub origin: AgentOrigin,
920    /// Who added it: the person who set it up, or the suggesting agent.
921    pub created_by: SubjectRef,
922    /// The person who approved its suggestion.
923    #[serde(default, skip_serializing_if = "Option::is_none")]
924    pub approved_by: Option<SubjectRef>,
925    /// When it was first stored.
926    pub created_at: DateTime<Utc>,
927    /// When it last changed.
928    pub updated_at: DateTime<Utc>,
929    /// 1 when first stored, one more with every change; the compare-and-set token.
930    pub version: u64,
931    /// The digest of its definition ([`AgentDefinition::digest`]).
932    pub digest: String,
933    /// The surface its last change was made on — `web`, `terminal`, `phone` — or `inbox`
934    /// for a suggestion approved where the kernel cannot tell; a change refused as out of
935    /// date names it (spec 3.3 §5.7).
936    #[serde(default, skip_serializing_if = "Option::is_none")]
937    pub changed_on: Option<String>,
938}
939
940impl AgentRecord {
941    /// A record of `definition` under `id`, at version 1, created at `at`.
942    pub fn new(
943        id: impl Into<String>,
944        definition: AgentDefinition,
945        state: AgentRecordState,
946        origin: AgentOrigin,
947        created_by: SubjectRef,
948        at: DateTime<Utc>,
949    ) -> Self {
950        let definition = definition.normalized();
951        Self {
952            id: id.into(),
953            digest: definition.digest(),
954            display_name: definition.display_name,
955            color: definition.color,
956            description: definition.description,
957            instructions: definition.instructions,
958            area: definition.area,
959            mode: definition.mode,
960            model: definition.model,
961            uses: definition.uses,
962            daily_limit_micro_usd: definition.daily_limit_micro_usd,
963            state,
964            origin,
965            created_by,
966            approved_by: None,
967            created_at: at,
968            updated_at: at,
969            version: 1,
970            changed_on: None,
971        }
972    }
973
974    /// Its definition.
975    pub fn definition(&self) -> AgentDefinition {
976        AgentDefinition {
977            display_name: self.display_name.clone(),
978            color: self.color,
979            description: self.description.clone(),
980            instructions: self.instructions.clone(),
981            area: self.area.clone(),
982            mode: self.mode,
983            model: self.model.clone(),
984            uses: self.uses.clone(),
985            daily_limit_micro_usd: self.daily_limit_micro_usd,
986        }
987    }
988
989    /// The record with `definition` in place of its own and the digest recomputed; the
990    /// area is the record's own whatever `definition` says (K-I15). The version and times
991    /// are the agent table's to move.
992    #[must_use]
993    pub fn with_definition(mut self, definition: AgentDefinition) -> Self {
994        let definition = definition.normalized();
995        self.digest = AgentDefinition { area: self.area.clone(), ..definition.clone() }.digest();
996        self.display_name = definition.display_name;
997        self.color = definition.color;
998        self.description = definition.description;
999        self.instructions = definition.instructions;
1000        self.mode = definition.mode;
1001        self.model = definition.model;
1002        self.uses = definition.uses;
1003        self.daily_limit_micro_usd = definition.daily_limit_micro_usd;
1004        self
1005    }
1006
1007    /// Sets the state.
1008    #[must_use]
1009    pub fn with_state(mut self, state: AgentRecordState) -> Self {
1010        self.state = state;
1011        self
1012    }
1013
1014    /// Sets the person who approved it.
1015    #[must_use]
1016    pub fn with_approved_by(mut self, by: SubjectRef) -> Self {
1017        self.approved_by = Some(by);
1018        self
1019    }
1020
1021    /// Sets the surface its last change was made on.
1022    #[must_use]
1023    pub fn with_changed_on(mut self, surface: impl Into<String>) -> Self {
1024        self.changed_on = Some(surface.into());
1025        self
1026    }
1027
1028    /// Checks the id ([`check_agent_id`]) and the definition ([`AgentDefinition::validate`]),
1029    /// and that the digest is the definition's.
1030    ///
1031    /// # Errors
1032    ///
1033    /// Returns a `kernel.agent.invalid` error saying which rule the record breaks.
1034    pub fn validate(&self) -> Result<()> {
1035        check_agent_id(&self.id)?;
1036        self.definition().validate()?;
1037        if self.digest != self.definition().digest() {
1038            return Err(invalid(format!(
1039                "agent `{}`: its digest is not its definition's; the record was changed \
1040                 outside the agent table",
1041                self.id
1042            )));
1043        }
1044        Ok(())
1045    }
1046
1047    /// The agent's identity in `area` (spec 3.3 §5.7): `urn:adk:agent:{app}/{id}` with the
1048    /// area's class, tenant and partition attribute, and as its sponsor the person who
1049    /// approved it, or who added it by hand.
1050    ///
1051    /// # Example
1052    ///
1053    /// ```rust
1054    /// use adk_core::principal::SubjectRef;
1055    /// use adk_kernel::agents::{AgentDefinition, AgentOrigin, AgentRecord, AgentRecordState};
1056    /// use adk_kernel::Partition;
1057    ///
1058    /// let record = AgentRecord::new("finance", AgentDefinition::new("Finance", "home"),
1059    ///     AgentRecordState::Active, AgentOrigin::ByHand, SubjectRef::human("alice"), chrono::Utc::now());
1060    /// let principal = record.principal("adk-rust", &Partition::new("home", "home"));
1061    /// assert_eq!(principal.id.as_str(), "urn:adk:agent:adk-rust/finance");
1062    /// assert_eq!(principal.class.as_deref(), Some("home"));
1063    /// assert_eq!(principal.sponsor, Some(SubjectRef::human("alice")));
1064    /// ```
1065    pub fn principal(&self, app_name: &str, area: &Partition) -> AgentPrincipal {
1066        let sponsor = self.approved_by.clone().unwrap_or_else(|| self.created_by.clone());
1067        area.principal(app_name, &self.id).with_sponsor(sponsor)
1068    }
1069
1070    /// The agent's id as an [`AgentId`]: `urn:adk:agent:{app}/{id}`.
1071    pub fn agent_id(&self, app_name: &str) -> AgentId {
1072        AgentPrincipal::derived(app_name, &self.id).id
1073    }
1074}
1075
1076/// Checks `id` against the id rules every added agent keeps (spec 3.3 §5.7): the pattern
1077/// `[a-z0-9][a-z0-9-]{0,39}` and no reserved id ([`RESERVED_AGENT_IDS`]); `@` and `.` never
1078/// match the pattern. The host's own targets are the agent table's to check.
1079///
1080/// # Errors
1081///
1082/// Returns a `kernel.agent.invalid` error.
1083///
1084/// # Example
1085///
1086/// ```rust
1087/// use adk_kernel::agents::check_agent_id;
1088///
1089/// assert!(check_agent_id("finance-2").is_ok());
1090/// assert!(check_agent_id("adk-rust").is_err());
1091/// assert!(check_agent_id("adk-rust@work").is_err());
1092/// assert!(check_agent_id("-finance").is_err());
1093/// ```
1094pub fn check_agent_id(id: &str) -> Result<()> {
1095    let mut chars = id.chars();
1096    let pattern = chars.next().is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
1097        && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
1098        && id.len() <= MAX_AGENT_ID_LEN;
1099    if !pattern {
1100        return Err(invalid(format!(
1101            "`{id}` is not an agent id: lowercase letters, digits and `-`, starting with a \
1102             letter or digit, at most {MAX_AGENT_ID_LEN} characters"
1103        )));
1104    }
1105    if RESERVED_AGENT_IDS.contains(&id) {
1106        return Err(invalid(format!("`{id}` is reserved for the kernel's own agents")));
1107    }
1108    Ok(())
1109}
1110
1111/// The id an agent named `display_name` gets (spec 3.3 §5.7, S-I14): its name in lowercase
1112/// ASCII letters and digits joined by `-`, at most [`MAX_AGENT_ID_LEN`] characters, or
1113/// [`FALLBACK_AGENT_ID`] when it has no letter or digit; then `-2`, `-3`, … while `taken`
1114/// says the id was ever used or is reserved.
1115///
1116/// # Example
1117///
1118/// ```rust
1119/// use adk_kernel::agents::agent_id_for;
1120///
1121/// assert_eq!(agent_id_for("Finance", |_| false), "finance");
1122/// assert_eq!(agent_id_for("Finance", |id| id == "finance"), "finance-2");
1123/// assert_eq!(agent_id_for("Bills & Taxes!", |_| false), "bills-taxes");
1124/// assert_eq!(agent_id_for("日本", |_| false), "agent");
1125/// assert_eq!(agent_id_for("…", |id| id == "agent"), "agent-2");
1126/// ```
1127pub fn agent_id_for(display_name: &str, taken: impl Fn(&str) -> bool) -> String {
1128    let mut base = String::new();
1129    for c in display_name.chars() {
1130        if c.is_ascii_alphanumeric() {
1131            base.push(c.to_ascii_lowercase());
1132        } else if c.is_ascii() && !base.is_empty() && !base.ends_with('-') {
1133            base.push('-');
1134        }
1135    }
1136    let mut base = base.trim_end_matches('-').to_string();
1137    if base.is_empty() {
1138        base = FALLBACK_AGENT_ID.to_string();
1139    }
1140    let fits = |base: &str, suffix: &str| {
1141        let room = MAX_AGENT_ID_LEN - suffix.len();
1142        let cut = &base[..base.len().min(room)];
1143        format!("{}{suffix}", cut.trim_end_matches('-'))
1144    };
1145    let usable = |id: &str| !taken(id) && check_agent_id(id).is_ok();
1146    let first = fits(&base, "");
1147    if usable(&first) {
1148        return first;
1149    }
1150    let mut n: u64 = 2;
1151    loop {
1152        let candidate = fits(&base, &format!("-{n}"));
1153        if usable(&candidate) {
1154            return candidate;
1155        }
1156        n += 1;
1157    }
1158}
1159
1160#[cfg(test)]
1161mod tests {
1162    use super::*;
1163
1164    fn record(id: &str) -> AgentRecord {
1165        AgentRecord::new(
1166            id,
1167            AgentDefinition::new("Finance", "default"),
1168            AgentRecordState::Active,
1169            AgentOrigin::ByHand,
1170            SubjectRef::human("alice"),
1171            Utc::now(),
1172        )
1173    }
1174
1175    #[test]
1176    fn ids_follow_the_pattern_and_skip_reserved_ones() {
1177        for id in ["finance", "a", "agent-2", "0day", &"a".repeat(40)] {
1178            assert!(check_agent_id(id).is_ok(), "{id}");
1179        }
1180        for id in [
1181            "",
1182            "Finance",
1183            "-finance",
1184            "fin.ance",
1185            "harness.goal",
1186            "adk-rust@work",
1187            "kernel.wake",
1188            "adk-rust",
1189            "self-improver",
1190            "finance_2",
1191            &"a".repeat(41),
1192        ] {
1193            assert!(check_agent_id(id).is_err(), "{id}");
1194        }
1195    }
1196
1197    #[test]
1198    fn a_removed_agents_id_is_never_given_again() {
1199        let mut ever = vec!["finance".to_string()];
1200        let second = agent_id_for("Finance", |id| ever.iter().any(|used| used == id));
1201        assert_eq!(second, "finance-2");
1202        ever.push(second);
1203        assert_eq!(agent_id_for("FINANCE", |id| ever.iter().any(|used| used == id)), "finance-3");
1204        // A name that would be reserved moves on to a free id.
1205        assert_eq!(agent_id_for("ADK-Rust", |_| false), "adk-rust-2");
1206        assert_eq!(agent_id_for("Self improver", |_| false), "self-improver-2");
1207    }
1208
1209    #[test]
1210    fn long_names_keep_ids_within_the_limit() {
1211        let name = "A very long agent name that goes on and on past forty characters";
1212        let first = agent_id_for(name, |_| false);
1213        assert!(first.len() <= MAX_AGENT_ID_LEN && !first.ends_with('-'), "{first}");
1214        let second = agent_id_for(name, |id| id == first);
1215        assert!(second.len() <= MAX_AGENT_ID_LEN && second.ends_with("-2"), "{second}");
1216        assert!(check_agent_id(&second).is_ok());
1217    }
1218
1219    #[test]
1220    fn names_and_folders_are_checked() {
1221        let base = AgentDefinition::new("Finance", "default");
1222        assert!(base.clone().validate().is_ok());
1223        for bad in ["", "   ", "You", "you", &"x".repeat(41), "Two\nlines"] {
1224            let mut definition = base.clone();
1225            definition.display_name = bad.to_string();
1226            assert!(definition.validate().is_err(), "{bad:?}");
1227        }
1228        for bad in ["../Mail", "Invoices/../../etc", "/etc", "\\\\server", "C:\\Users", "~/x"] {
1229            let definition = base
1230                .clone()
1231                .with_uses(AgentUses::default().with_files(FileAccess::Read).with_folder(bad));
1232            assert!(definition.validate().is_err(), "{bad}");
1233        }
1234        let nested = base
1235            .clone()
1236            .with_uses(AgentUses::default().with_folder("./Invoices//2026/"))
1237            .normalized();
1238        assert_eq!(nested.uses.folder.as_deref(), Some("Invoices/2026"));
1239        let long = base.clone().with_instructions("x".repeat(MAX_AGENT_INSTRUCTIONS_LEN + 1));
1240        assert!(long.validate().is_err());
1241        assert!(base.clone().with_daily_limit(0).validate().is_err());
1242        let hosts = base
1243            .clone()
1244            .with_uses(AgentUses::default().with_web(WebAccess::listed(["https://x.io/a"])));
1245        assert!(hosts.validate().is_err());
1246    }
1247
1248    /// Wave 3 finding 27: a name that draws like "ADK-Rust" but holds an invisible character
1249    /// is refused, as is a line holding one.
1250    #[test]
1251    fn invisible_characters_are_refused_in_names_and_lines() {
1252        let base = AgentDefinition::new("Finance", "default");
1253        for bad in ["ADK-Rust\u{200b}", "Fin\u{200d}ance", "\u{202e}ecnaniF", "You\u{feff}"] {
1254            let mut definition = base.clone();
1255            definition.display_name = bad.to_string();
1256            assert!(definition.validate().is_err(), "{bad:?}");
1257        }
1258        let line = base.clone().with_description("Reads\u{2066} invoices");
1259        assert!(line.validate().is_err());
1260        let mut accented = base;
1261        accented.display_name = "Facturación".into();
1262        assert!(accented.validate().is_ok());
1263    }
1264
1265    #[test]
1266    fn the_digest_covers_the_definition_only() {
1267        let first = record("finance");
1268        let mut later = first.clone().with_state(AgentRecordState::Paused);
1269        later.version = 7;
1270        later.updated_at = first.updated_at + chrono::Duration::hours(1);
1271        later.origin = AgentOrigin::Suggested {
1272            agent: AgentId::new("urn:adk:agent:adk-rust/adk-rust").unwrap(),
1273            session: "s".into(),
1274            run: None,
1275            unattended: true,
1276        };
1277        assert_eq!(first.digest, later.digest);
1278        let renamed = first.clone().with_definition(first.definition().with_description("Bills"));
1279        assert_ne!(first.digest, renamed.digest);
1280        assert!(renamed.validate().is_ok());
1281        // Order and spacing of sets do not change it.
1282        let a = AgentDefinition::new(" Finance ", "default")
1283            .with_uses(AgentUses::default().with_pack("b").with_pack("a").with_pack("a"));
1284        let b = AgentDefinition::new("Finance", "default")
1285            .with_color(a.color)
1286            .with_uses(AgentUses::default().with_pack("a").with_pack("b"));
1287        assert_eq!(a.digest(), b.digest());
1288    }
1289
1290    #[test]
1291    fn a_change_never_moves_the_area() {
1292        let record = record("finance");
1293        let moved = record.clone().with_definition(AgentDefinition::new("Finance", "work"));
1294        assert_eq!(moved.area.as_str(), "default");
1295        assert!(moved.validate().is_ok());
1296    }
1297
1298    #[test]
1299    fn the_wire_form_refuses_unknown_fields() {
1300        let mut wire = serde_json::to_value(record("finance")).unwrap();
1301        wire["apiKey"] = serde_json::json!("sk-123");
1302        assert!(serde_json::from_value::<AgentRecord>(wire).is_err());
1303    }
1304
1305    #[test]
1306    fn colors_match_the_surface_palette_hash() {
1307        // FNV-1a of "ADK-Rust" over eight colours, as adk-surface's avatar picks it.
1308        let hash = "ADK-Rust".bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
1309            (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
1310        });
1311        assert_eq!(AvatarColor::for_name("ADK-Rust").index(), (hash % 8) as usize);
1312        for (index, color) in AvatarColor::ALL.into_iter().enumerate() {
1313            assert_eq!(color.index(), index);
1314            assert_eq!(color.as_str().parse::<AvatarColor>().unwrap(), color);
1315        }
1316    }
1317
1318    #[test]
1319    fn uses_over_a_ceiling_are_named() {
1320        let ceiling = AgentUses::default()
1321            .with_files(FileAccess::Read)
1322            .with_web(WebAccess::listed(["example.com"]))
1323            .with_pack("search")
1324            .with_driver("calendar");
1325        let within = AgentUses::default()
1326            .with_files(FileAccess::Read)
1327            .with_web(WebAccess::listed(["example.com"]))
1328            .with_driver("calendar");
1329        assert!(within.over(&ceiling).is_empty());
1330        let over = AgentUses::default()
1331            .with_files(FileAccess::ReadWrite)
1332            .with_shell(ShellAccess::Host)
1333            .with_web(WebAccess::listed(["example.com", "evil.test"]))
1334            .with_pack("payments")
1335            .with_driver("mail");
1336        assert_eq!(
1337            over.over(&ceiling),
1338            [
1339                "changing files",
1340                "a shell on this computer",
1341                "the sites evil.test",
1342                "the payments pack",
1343                "the mail driver"
1344            ]
1345        );
1346        assert_eq!(AgentUses::default().with_web(WebAccess::Any).over(&ceiling), ["any site"]);
1347    }
1348}