use serde::{Deserialize, Serialize};
pub use tilo_action_policy::ActionKind;
use crate::action::{OperationKind, undo_takes_back};
use crate::context::ChangeKind;
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(remote = "Self", tag = "state", rename_all = "snake_case")]
pub enum Availability {
#[default]
Available,
Unavailable {
code: String,
reason: String,
},
}
read_through_json_value!(Availability);
impl Availability {
pub const NOT_ALLOWED: &'static str = "not_allowed";
pub fn is_available(&self) -> bool {
matches!(self, Self::Available)
}
#[must_use]
pub fn not_allowed(by: Option<tilo_action_policy::Refuser>) -> Self {
let reason = match by {
Some(tilo_action_policy::Refuser::Settings) => {
"the person you work for set this to Deny for you in this workspace; they can \
change it under Workspace settings → Agents"
}
Some(tilo_action_policy::Refuser::Workspace) => {
"this workspace's own rules don't let agents or keys do this here"
}
None => Self::NOT_ALLOWED_HERE,
};
Self::Unavailable {
code: Self::NOT_ALLOWED.to_owned(),
reason: reason.to_owned(),
}
}
pub const NOT_ALLOWED_HERE: &'static str = "this workspace's permissions don't let you do \
this here; the person you work for can change what you may do under Workspace \
settings → Agents";
pub const PRIVATE_VIEW: &'static str = "private_view";
#[must_use]
pub fn shown_here() -> Self {
Self::Unavailable {
code: Self::PRIVATE_VIEW.to_owned(),
reason: Self::SHOWN_HERE.to_owned(),
}
}
pub const SHOWN_HERE: &'static str =
"only changes what the person at this device sees; only they invoke it";
#[must_use]
pub fn refusal(&self) -> Option<(&str, &str)> {
match self {
Self::Unavailable { code, reason }
if code == Self::NOT_ALLOWED || code == Self::PRIVATE_VIEW =>
{
Some((code, reason))
}
Self::Available | Self::Unavailable { .. } => None,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RiskLevel {
None,
#[default]
Low,
Destructive,
Privileged,
Sensitive,
}
impl RiskLevel {
pub fn requires_confirmation(self) -> bool {
matches!(self, Self::Destructive | Self::Privileged | Self::Sensitive)
}
#[must_use]
pub fn requires_confirmation_when(self, can_be_undone: bool) -> bool {
match self {
Self::Destructive => !can_be_undone,
Self::Privileged | Self::Sensitive => true,
Self::None | Self::Low => false,
}
}
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::None => "none",
Self::Low => "low",
Self::Destructive => "destructive",
Self::Privileged => "privileged",
Self::Sensitive => "sensitive",
}
}
#[must_use]
pub fn from_name(name: &str) -> Option<Self> {
[
Self::None,
Self::Low,
Self::Destructive,
Self::Privileged,
Self::Sensitive,
]
.into_iter()
.find(|level| level.name() == name)
}
}
pub const MEMBER_OWN_TAG: &str = "host:member-own";
pub const HOST_RENDER_TAG: &str = "host:render";
pub const AGENTS_AUDIENCE_TAG: &str = "audience:agents";
pub const PEOPLE_AUDIENCE_TAG: &str = "audience:people";
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Audience {
#[default]
Everyone,
People,
Agents,
}
impl Audience {
pub const fn reaches_people(self) -> bool {
!matches!(self, Self::Agents)
}
pub const fn reaches_agents(self) -> bool {
!matches!(self, Self::People)
}
pub const fn tag(self) -> Option<&'static str> {
match self {
Self::Everyone => None,
Self::People => Some(PEOPLE_AUDIENCE_TAG),
Self::Agents => Some(AGENTS_AUDIENCE_TAG),
}
}
}
pub const UNTRUSTED_CONTENT_TAG: &str = "content:untrusted";
pub const ARGUMENT_RISK_TAG: &str = "confirmation:by-argument";
pub const CARRIER_TAG: &str = "carries:actions";
pub const FIELD_EDIT_PARAM: &str = "edit";
fn edit_parts(
edit: &serde_json::Value,
) -> Option<(&str, Vec<tilo_action_policy::edits::EditStep<'_>>)> {
use tilo_action_policy::edits::EditStep;
let op = edit.get("op")?.as_str()?;
let path = edit
.get("path")?
.as_array()?
.iter()
.map(|step| {
let (kind, value) = step.as_object()?.iter().next()?;
Some(match kind.as_str() {
"field" => EditStep::Field(value.as_str()?),
_ => EditStep::Item,
})
})
.collect::<Option<Vec<_>>>()?;
Some((op, path))
}
pub const ROUTED_CHANGE_TAG: &str = "routed:document-change";
pub const DOCUMENT_READ_TAG: &str = "read:document";
pub const RESOURCE_READ_TAG: &str = "read:record";
pub const OPENS_PATH_TAG: &str = "open:path";
pub const REQUIRES_HOST_PREFIX: &str = "requires-host:";
pub const REQUIRES_NATIVE_PATHS_TAG: &str = "requires-host:native-paths";
pub const HOST_UNSUPPORTED_CODE: &str = "host_unsupported";
pub const OPENS_PATH_EXTENSION_PREFIX: &str = "open:path-ext:";
pub const OUTSIDE_CAPABILITY_PREFIX: &str = "outside:";
pub const SEARCH_TAG: &str = "search";
pub const SEARCH_KIND_PREFIX: &str = "search_kind:";
pub const INCOMING_MESSAGE_FACET: &str = "incoming-message";
pub const INCOMING_MESSAGE_TAG: &str = "trigger:incoming-message";
pub const ORIGIN_FACET: &str = "origin";
pub const READERS_FACET: &str = "readers";
#[must_use]
pub fn readers_facet(readers: &[crate::MemberId]) -> String {
let named: Vec<String> = readers.iter().map(reader_name).collect();
serde_json::Value::from(named).to_string()
}
#[must_use]
pub fn reader_name(member: &crate::MemberId) -> String {
String::from_utf8_lossy(&member.actor_bytes()).into_owned()
}
#[must_use]
pub fn readers_named(facets: &[crate::ActionFacet]) -> Option<Vec<String>> {
let facet = facets.iter().find(|facet| facet.key == READERS_FACET)?;
Some(tilo_failure::ignored!(
"a readers list that does not read names nobody, which keeps the change from everyone",
serde_json::from_str(&facet.value).unwrap_or_default()
))
}
#[must_use]
pub fn reads_change(facets: &[crate::ActionFacet], reader: Option<&crate::MemberId>) -> bool {
readers_named(facets)
.is_none_or(|named| reader.is_some_and(|reader| named.contains(&reader_name(reader))))
}
pub const COMPENSATED_UNDO_TAG: &str = "undo:compensated";
pub const IRREVERSIBLE_TAG: &str = "undo:irreversible";
pub const HOUSEKEEPING_TAG: &str = "change:housekeeping";
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ActionNeed {
pub kind: ActionKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub field: Option<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub privileged: bool,
}
#[must_use]
pub fn resource_node(
base: &tilo_action_policy::TreePath,
app: &str,
resource_kind: &str,
resource: &str,
) -> tilo_action_policy::TreePath {
let (resource_kind, resource) =
if tilo_action_policy::roles::is_workspace_moderation(app, resource)
|| (resource_kind == "tilo.moderation"
&& resource == resource_kind
&& tilo_action_policy::roles::is_workspace_moderation(
app,
tilo_action_policy::roles::WORKSPACE_MODERATION_DOCUMENT,
))
{
("chat.workspace", "")
} else {
(resource_kind, resource)
};
base.clone().app(app).kind(resource_kind).resource(resource)
}
#[must_use]
pub fn action_node(
base: &tilo_action_policy::TreePath,
app: &str,
resource_kind: &str,
resource: &str,
field: Option<&str>,
action: &str,
) -> tilo_action_policy::TreePath {
let node = resource_node(base, app, resource_kind, resource);
match field {
Some(field) => node.field(field),
None => node,
}
.action(action)
}
impl ActionNeed {
#[must_use]
pub const fn of(kind: ActionKind) -> Self {
Self {
kind,
field: None,
privileged: false,
}
}
#[must_use]
pub fn comments() -> Self {
Self {
kind: ActionKind::Undoable,
field: Some(tilo_action_policy::roles::COMMENTS_FIELD.to_owned()),
privileged: false,
}
}
#[must_use]
pub fn reactions() -> Self {
Self {
kind: ActionKind::Undoable,
field: Some(tilo_action_policy::roles::REACTIONS_FIELD.to_owned()),
privileged: false,
}
}
#[must_use]
pub fn moderation() -> Self {
Self {
kind: ActionKind::Undoable,
field: Some(tilo_action_policy::roles::MODERATION_FIELD.to_owned()),
privileged: false,
}
}
}
const fn undoable() -> ActionKind {
ActionKind::Undoable
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(remote = "Self", tag = "mode", rename_all = "snake_case")]
pub enum ConfirmationPolicy {
#[default]
None,
Confirm,
Phrase {
phrase: String,
},
}
read_through_json_value!(ConfirmationPolicy);
const GENERIC_CONFIRMATION_WORDS: &[&str] = &[
"confirm",
"confirmed",
"yes",
"ok",
"okay",
"sure",
"agree",
"i agree",
"continue",
"proceed",
"accept",
"delete",
"remove",
"erase",
"wipe",
"reset",
"destroy",
];
#[must_use]
pub fn phrase_is_meaningful(phrase: &str) -> bool {
let phrase = phrase.trim();
!phrase.is_empty()
&& !GENERIC_CONFIRMATION_WORDS
.iter()
.any(|word| phrase.eq_ignore_ascii_case(word))
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RetryPolicy {
Idempotent,
RetryWithInvocationId,
#[default]
AtMostOnce,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(remote = "Self", tag = "mode", rename_all = "snake_case")]
pub enum ExecutionMode {
#[default]
Immediate,
Background { cancellable: bool },
Streaming {
cancellable: bool,
item_schema: serde_json::Value,
},
Live { item_schema: serde_json::Value },
}
read_through_json_value!(ExecutionMode);
impl ExecutionMode {
#[must_use]
pub const fn cancellable(&self) -> bool {
matches!(
self,
Self::Background { cancellable: true }
| Self::Streaming {
cancellable: true,
..
}
| Self::Live { .. }
)
}
#[must_use]
pub const fn item_schema(&self) -> Option<&serde_json::Value> {
match self {
Self::Streaming { item_schema, .. } | Self::Live { item_schema } => Some(item_schema),
Self::Immediate | Self::Background { .. } => None,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(remote = "Self", tag = "type", rename_all = "snake_case")]
pub enum ResultSpec {
#[default]
None,
Json {
schema: serde_json::Value,
},
Resource {
resource_kind: String,
},
Job,
}
read_through_json_value!(ResultSpec);
pub const MADE_FIELDS: [&str; 3] = ["made", "minted", "wrote"];
impl crate::ActionOutput {
#[must_use]
pub fn declared(&self) -> Option<serde_json::Value> {
let value = self.value.as_ref()?;
let Some(fields) = value.as_object() else {
return Some(value.clone());
};
let kept: serde_json::Map<String, serde_json::Value> = fields
.iter()
.filter(|(key, _)| !MADE_FIELDS.contains(&key.as_str()))
.map(|(key, value)| (key.clone(), value.clone()))
.collect();
if fields.is_empty() {
return Some(serde_json::Value::Object(kept));
}
(!kept.is_empty()).then_some(serde_json::Value::Object(kept))
}
}
impl ResultSpec {
pub fn validate(&self, output: &crate::ActionOutput) -> Result<(), String> {
let declared = output.declared();
match self {
Self::None | Self::Job if declared.is_none() => Ok(()),
Self::None => Err("action declared no result but returned one".into()),
Self::Json { schema } => match declared.or_else(|| output.value.clone()) {
Some(value) => crate::params::validate_schema(&value, schema),
None => crate::params::validate_schema(&serde_json::Value::Null, schema)
.map_err(|_| "action did not return its declared JSON result".to_string()),
},
Self::Resource { resource_kind }
if !output.resources.is_empty()
&& output.resources.iter().all(|address| {
address == resource_kind
|| address.strip_prefix(resource_kind).is_some_and(|suffix| {
suffix.starts_with(':') || suffix.starts_with('/')
})
}) =>
{
Ok(())
}
Self::Resource { resource_kind } => Err(format!(
"action did not return a `{resource_kind}` resource address"
)),
Self::Job => Err("job action returned an undeclared terminal value".into()),
}
}
}
pub const ATTENDED_TAG: &str = "tilo.attended";
pub const SCREEN_TAG: &str = "tilo.screen";
pub const SCREEN_PLACE_TAG: &str = "tilo.screen.place";
pub const SECRET_ANSWER_TAG: &str = "tilo.answer.secret";
pub const ROOT_ONLY_TAG: &str = "tilo.root-only";
pub const OWN_DEVICE_SCOPE: &str = "tilo.scope.own-device";
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ActionContract {
#[serde(default)]
pub availability: Availability,
#[serde(default = "undoable")]
pub kind: ActionKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub field: Option<String>,
#[serde(default)]
pub risk: RiskLevel,
#[serde(default)]
pub confirmation: ConfirmationPolicy,
#[serde(default)]
pub retry: RetryPolicy,
#[serde(default)]
pub execution: ExecutionMode,
#[serde(default)]
pub result: ResultSpec,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tags: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub offload: Option<Offload>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub step: Option<crate::StepKind>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub creates: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub item: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub shows: Vec<crate::remote::asked::Shown>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub takes: Vec<crate::remote::asked::Take>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub effects: Vec<crate::ActionEffect>,
}
pub const MAX_OFFLOAD_CPU_TIME_MS: u64 = 5 * 60 * 1_000;
pub const MAX_OFFLOAD_MEMORY_BYTES: u64 = 8 * 1024 * 1024 * 1024;
pub const MIN_OFFLOAD_MEMORY_BYTES: u64 = 16 * 1024 * 1024;
pub const MAX_OFFLOAD_OUTPUT_BYTES: u64 = 16 * 1024 * 1024;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Offload {
#[serde(default)]
pub gpu: bool,
pub cpu_time_ms: u64,
pub memory_bytes: u64,
pub output_bytes: u64,
}
impl Offload {
#[must_use]
pub fn validate(&self) -> Vec<String> {
let mut errors = Vec::new();
if self.cpu_time_ms == 0 || self.cpu_time_ms > MAX_OFFLOAD_CPU_TIME_MS {
errors.push("offload cpu time is outside the compute bounds".into());
}
if !(MIN_OFFLOAD_MEMORY_BYTES..=MAX_OFFLOAD_MEMORY_BYTES).contains(&self.memory_bytes) {
errors.push("offload memory is outside the compute bounds".into());
}
if self.output_bytes == 0 || self.output_bytes > MAX_OFFLOAD_OUTPUT_BYTES {
errors.push("offload output is outside the compute bounds".into());
}
errors
}
}
impl Default for ActionContract {
fn default() -> Self {
Self {
availability: Availability::Available,
kind: ActionKind::Undoable,
field: None,
risk: RiskLevel::Low,
confirmation: ConfirmationPolicy::None,
retry: RetryPolicy::AtMostOnce,
execution: ExecutionMode::Immediate,
result: ResultSpec::None,
tags: Vec::new(),
offload: None,
step: None,
creates: None,
item: None,
shows: Vec::new(),
takes: Vec::new(),
effects: Vec::new(),
}
}
}
impl ActionContract {
#[must_use]
pub fn declares(&self, provider: &str, address: &crate::ActionAddress) -> bool {
self.effects.iter().any(|effect| {
effect.app == provider
&& effect.kind == address.resource
&& effect.verb == address.action
})
}
#[must_use]
pub fn need(&self) -> ActionNeed {
self.scoped(ActionNeed {
kind: self.kind,
field: self.field.clone(),
privileged: self.risk == RiskLevel::Privileged,
})
}
#[must_use]
pub fn scoped(&self, mut need: ActionNeed) -> ActionNeed {
if need.kind == ActionKind::Outside && self.runs_on_invokers_device() {
need.kind = ActionKind::Read;
}
need
}
pub fn view() -> Self {
Self {
risk: RiskLevel::None,
kind: ActionKind::Read,
retry: RetryPolicy::Idempotent,
..Self::default()
}
}
pub fn live_view(item_schema: serde_json::Value) -> Self {
Self {
execution: ExecutionMode::Live { item_schema },
..Self::view()
}
}
#[must_use]
pub const fn is_live(&self) -> bool {
matches!(self.execution, ExecutionMode::Live { .. })
}
pub fn for_operation(operation: OperationKind) -> Self {
match operation {
OperationKind::View => Self::view(),
OperationKind::Document => Self::default(),
OperationKind::Effect => Self {
kind: ActionKind::Outside,
..Self::default()
},
}
}
pub fn is_own_device(&self) -> bool {
self.tags.iter().any(|tag| tag == OWN_DEVICE_SCOPE)
}
pub fn is_attended(&self) -> bool {
self.tags.iter().any(|tag| tag == ATTENDED_TAG)
}
pub fn runs_on_invokers_device(&self) -> bool {
self.is_own_device() || self.is_attended()
}
pub fn only_shows(&self) -> bool {
self.tags.iter().any(|tag| tag == SCREEN_TAG) && !self.shows_a_place()
}
pub fn root_only(&self) -> bool {
self.tags.iter().any(|tag| tag == ROOT_ONLY_TAG)
}
pub fn answers_a_secret(&self) -> bool {
self.tags.iter().any(|tag| tag == SECRET_ANSWER_TAG)
}
pub fn shows_a_place(&self) -> bool {
self.tags.iter().any(|tag| tag == SCREEN_PLACE_TAG)
}
pub fn screen() -> Self {
let mut contract = Self::view();
contract.tags.push(SCREEN_TAG.to_owned());
contract
}
pub fn audience(&self) -> Audience {
if self.tags.iter().any(|tag| tag == AGENTS_AUDIENCE_TAG) {
Audience::Agents
} else if self.tags.iter().any(|tag| tag == PEOPLE_AUDIENCE_TAG) {
Audience::People
} else {
Audience::Everyone
}
}
pub fn set_audience(&mut self, audience: Audience) {
self.tags
.retain(|tag| tag != AGENTS_AUDIENCE_TAG && tag != PEOPLE_AUDIENCE_TAG);
if let Some(tag) = audience.tag() {
self.tags.push(tag.to_owned());
}
}
pub fn reaches_people(&self) -> bool {
self.audience().reaches_people()
}
pub fn reaches_agents(&self) -> bool {
self.audience().reaches_agents()
}
#[must_use]
pub fn needs_an_item(&self) -> bool {
self.item.is_some()
}
#[must_use]
pub fn offered_to_people(&self) -> bool {
self.reaches_people() && !self.needs_an_item()
}
#[must_use]
pub fn a_person_can_take_now(&self) -> bool {
self.offered_to_people() && self.availability.is_available()
}
#[must_use]
pub fn offered_to_agents(&self) -> bool {
self.reaches_agents() && !self.needs_an_item()
}
pub fn reads_document(&self) -> bool {
self.tags.iter().any(|tag| tag == DOCUMENT_READ_TAG)
}
pub fn reads_resource(&self) -> bool {
self.reads_document() || self.tags.iter().any(|tag| tag == RESOURCE_READ_TAG)
}
pub fn discloses_resource(&self) -> bool {
self.reads_resource() || self.is_presence_view()
}
pub fn disclosure_rank(&self) -> u8 {
if self.reads_document() {
0
} else if self.reads_resource() {
1
} else {
2
}
}
pub fn opens_path(&self) -> bool {
self.tags.iter().any(|tag| tag == OPENS_PATH_TAG)
}
pub fn opened_extensions(&self) -> impl Iterator<Item = &str> {
self.tags
.iter()
.filter_map(|tag| tag.strip_prefix(OPENS_PATH_EXTENSION_PREFIX))
}
pub fn carries_untrusted_content(&self) -> bool {
self.tags.iter().any(|tag| tag == UNTRUSTED_CONTENT_TAG)
}
#[must_use]
pub fn carries_actions(&self) -> bool {
self.tags.iter().any(|tag| tag == CARRIER_TAG)
}
pub fn outside_capabilities(&self) -> impl Iterator<Item = &str> {
self.tags
.iter()
.filter_map(|tag| tag.strip_prefix(OUTSIDE_CAPABILITY_PREFIX))
}
pub fn can_be_undone(&self) -> bool {
(self.kind == ActionKind::Undoable
|| self.tags.iter().any(|tag| tag == COMPENSATED_UNDO_TAG))
&& !self.tags.iter().any(|tag| tag == IRREVERSIBLE_TAG)
}
#[must_use]
pub fn requires_confirmation(&self) -> bool {
self.risk.requires_confirmation_when(self.can_be_undone())
}
pub fn settle_confirmation(&mut self) {
if self.risk != RiskLevel::Destructive {
return;
}
let undoable = undo_takes_back(
self.settled_kind(),
ChangeKind::Content,
self.tags.iter().any(|tag| tag == IRREVERSIBLE_TAG),
);
match (&self.confirmation, undoable) {
(ConfirmationPolicy::Confirm, true) => self.confirmation = ConfirmationPolicy::None,
(ConfirmationPolicy::None, false) => self.confirmation = ConfirmationPolicy::Confirm,
_ => {}
}
}
#[must_use]
pub fn settled_kind(&self) -> ActionKind {
let irreversible = self.tags.iter().any(|tag| tag == IRREVERSIBLE_TAG);
let undoable = self.kind == ActionKind::Undoable
|| self.tags.iter().any(|tag| tag == COMPENSATED_UNDO_TAG);
if undoable && !irreversible {
return ActionKind::Undoable;
}
if self.kind == ActionKind::Undoable {
return ActionKind::Outside;
}
self.kind
}
#[must_use]
pub fn deletion_kind(&self) -> ActionKind {
let irreversible = self.tags.iter().any(|tag| tag == IRREVERSIBLE_TAG);
let kind = self.settled_kind();
if undo_takes_back(kind, ChangeKind::Content, irreversible) {
kind
} else {
ActionKind::Outside
}
}
pub fn confirmation_depends_on_arguments(&self) -> bool {
self.tags.iter().any(|tag| tag == ARGUMENT_RISK_TAG)
}
pub fn advertised_confirmation(&self) -> ConfirmationPolicy {
if self.confirmation == ConfirmationPolicy::None
&& self.confirmation_depends_on_arguments()
&& !self.can_be_undone()
{
ConfirmationPolicy::Confirm
} else {
self.confirmation.clone()
}
}
pub fn asks_for_argument(&self, argument: Option<&str>) -> bool {
self.is_attended() || self.confirmation_for_argument(argument) != ConfirmationPolicy::None
}
pub fn confirmation_for_argument(&self, argument: Option<&str>) -> ConfirmationPolicy {
if self.confirmation != ConfirmationPolicy::None
|| !self.confirmation_depends_on_arguments()
|| !self
.tags
.iter()
.any(|tag| tag == tilo_action_policy::edits::FIELD_EDIT_TAG)
{
return self.advertised_confirmation();
}
let edit = argument
.and_then(|text| text.strip_prefix(crate::ARGUMENTS_JSON_PREFIX))
.and_then(|json| serde_json::from_str::<serde_json::Value>(json).ok())
.and_then(|arguments| arguments.get(FIELD_EDIT_PARAM).cloned());
let tagged = |prefix: &str| -> Vec<&str> {
self.tags
.iter()
.filter_map(|tag| tag.strip_prefix(prefix))
.collect()
};
let quiet = tagged(tilo_action_policy::edits::QUIET_REMOVAL_TAG);
let guarded = tagged(tilo_action_policy::edits::GUARDED_FIELD_TAG);
let weakening: Vec<_> = tagged(tilo_action_policy::edits::WEAKENING_FIELD_TAG)
.into_iter()
.filter_map(tilo_action_policy::edits::WeakeningField::parse)
.collect();
let value = edit
.as_ref()
.and_then(|edit| edit.get("value"))
.map(serde_json::Value::to_string);
let undoable = self.can_be_undone();
let asks = |op: &str, path: &[tilo_action_policy::edits::EditStep<'_>]| {
if undoable {
tilo_action_policy::edits::guarded_at(path, &guarded)
} else {
tilo_action_policy::edits::field_edit_asks(op, path, &quiet, &guarded)
}
};
match edit.as_ref().and_then(edit_parts) {
Some((op, path))
if !asks(op, &path)
&& !tilo_action_policy::edits::weakening_edit(
op,
&path,
value.as_deref(),
&weakening,
) =>
{
ConfirmationPolicy::None
}
None if undoable && guarded.is_empty() && weakening.is_empty() => {
ConfirmationPolicy::None
}
_ => ConfirmationPolicy::Confirm,
}
}
pub fn validate_declaration(&self) -> Vec<String> {
let mut errors = Vec::new();
if let Availability::Unavailable { code, reason } = &self.availability
&& (code.trim().is_empty() || reason.trim().is_empty())
{
errors.push("unavailable action needs a code and reason".into());
}
if self.requires_confirmation() && matches!(self.confirmation, ConfirmationPolicy::None) {
errors.push("consequential action requires confirmation".into());
}
if let ConfirmationPolicy::Phrase { phrase } = &self.confirmation {
if phrase.trim().is_empty() {
errors.push("confirmation phrase must not be empty".into());
} else if !phrase_is_meaningful(phrase) {
errors.push(format!(
"confirmation phrase \"{phrase}\" says nothing about what is lost; name it (the drive, the app, the item)"
));
}
if self.can_be_undone() {
errors.push(
"an action Undo takes back is never confirmed by typing; it runs at once and offers Undo".into(),
);
}
}
if matches!(self.retry, RetryPolicy::RetryWithInvocationId) {
errors.push(
"retry_with_invocation_id requires a caller-supplied deduplication key, which this transport does not yet expose".into(),
);
}
if matches!(self.execution, ExecutionMode::Background { .. })
&& matches!(self.result, ResultSpec::None)
{
errors.push("background action must declare a result or job".into());
}
if matches!(self.execution, ExecutionMode::Immediate)
&& matches!(self.result, ResultSpec::Job)
{
errors.push("immediate action cannot declare a background job result".into());
}
if let Some(item_schema) = self.execution.item_schema()
&& let Err(reason) = crate::params::validate_schema_definition(item_schema)
{
errors.push(format!("invalid streaming item {reason}"));
}
if self.is_live() && self.kind != ActionKind::Read {
errors.push("a live result must be a read".into());
}
if let ResultSpec::Json { schema } = &self.result
&& let Err(reason) = crate::params::validate_schema_definition(schema)
{
errors.push(format!("invalid result {reason}"));
}
if self.tags.iter().any(|tag| tag.trim().is_empty()) {
errors.push("contract tags must not be empty".into());
}
let unique_tags = self.tags.iter().collect::<std::collections::HashSet<_>>();
if unique_tags.len() != self.tags.len() {
errors.push("contract tags must be unique".into());
}
if let Some(offload) = &self.offload {
errors.extend(offload.validate());
if self.kind != ActionKind::Read {
errors.push("an offloadable action must be a read".into());
}
}
errors
}
}
#[cfg(test)]
mod tests {
use super::*;
fn risk_level_keeps_existing_compact_wire_discriminants() {
assert_eq!(postcard::to_allocvec(&RiskLevel::None).unwrap(), vec![0]);
assert_eq!(postcard::to_allocvec(&RiskLevel::Low).unwrap(), vec![1]);
assert_eq!(
postcard::to_allocvec(&RiskLevel::Destructive).unwrap(),
vec![2]
);
assert_eq!(
postcard::to_allocvec(&RiskLevel::Privileged).unwrap(),
vec![3]
);
assert_eq!(
postcard::from_bytes::<RiskLevel>(&[2]).unwrap(),
RiskLevel::Destructive
);
assert_eq!(
postcard::from_bytes::<RiskLevel>(&[3]).unwrap(),
RiskLevel::Privileged
);
}
fn broker_owned_job_identity_is_not_a_second_application_result() {
assert!(
ResultSpec::Job
.validate(&crate::ActionOutput::default())
.is_ok()
);
assert!(
ResultSpec::Job
.validate(&crate::ActionOutput {
value: Some(serde_json::json!("a second job id")),
resources: Vec::new(),
})
.is_err()
);
}
#[test]
fn what_a_write_made_rides_beside_the_result_it_declared() {
let made = crate::ActionOutput {
value: Some(serde_json::json!({
"made": [{"id": "a1", "address": "notes.page/pages/a1"}],
"minted": ["a1"],
})),
resources: vec!["notes.page/pages/a1".into()],
};
assert!(ResultSpec::None.validate(&made).is_ok());
assert!(ResultSpec::Job.validate(&made).is_ok());
let schema = serde_json::json!({"type": "object", "required": ["count"],
"properties": {"count": {"type": "integer"}}});
let with_count = crate::ActionOutput {
value: Some(serde_json::json!({
"count": 2,
"made": [{"id": "a1", "address": "notes.page/pages/a1"}],
})),
resources: Vec::new(),
};
assert!(ResultSpec::Json { schema }.validate(&with_count).is_ok());
assert!(
ResultSpec::None
.validate(&crate::ActionOutput {
value: Some(serde_json::json!({"count": 2})),
resources: Vec::new(),
})
.is_err(),
"a result an action did not declare is still refused"
);
}
tilo_test_env::scenario! {
fn a_contract_declares_consent_audience_and_wire_shape;
phase an_attended_or_own_device_effect_needs_no_workspace_consent;
{
let outside = ActionContract::for_operation(OperationKind::Effect);
assert_eq!(outside.need().kind, ActionKind::Outside);
assert!(!outside.runs_on_invokers_device());
for tag in [ATTENDED_TAG, OWN_DEVICE_SCOPE] {
let mut contract = outside.clone();
contract.tags.push(tag.to_owned());
assert_eq!(contract.need().kind, ActionKind::Read, "{tag}");
assert!(contract.runs_on_invokers_device(), "{tag}");
}
}
phase undoable_deletes_ask_nothing_and_typed_phrases_name_what_is_lost;
{
let mut contract = ActionContract {
risk: RiskLevel::Destructive,
..ActionContract::default()
};
contract.settle_confirmation();
assert_eq!(contract.confirmation, ConfirmationPolicy::None);
assert!(!contract.requires_confirmation());
assert!(contract.validate_declaration().is_empty());
let mut compensated = ActionContract {
risk: RiskLevel::Destructive,
confirmation: ConfirmationPolicy::Confirm,
tags: vec![COMPENSATED_UNDO_TAG.to_owned()],
..ActionContract::default()
};
compensated.settle_confirmation();
assert_eq!(compensated.confirmation, ConfirmationPolicy::None);
let mut irreversible = ActionContract {
kind: ActionKind::Outside,
risk: RiskLevel::Destructive,
..ActionContract::default()
};
irreversible.settle_confirmation();
assert_eq!(irreversible.confirmation, ConfirmationPolicy::Confirm);
assert!(irreversible.requires_confirmation());
let mut forgets = ActionContract {
kind: ActionKind::Outside,
risk: RiskLevel::Destructive,
tags: vec![IRREVERSIBLE_TAG.to_owned()],
..ActionContract::default()
};
forgets.settle_confirmation();
assert_eq!(forgets.confirmation, ConfirmationPolicy::Confirm);
assert!(RiskLevel::Privileged.requires_confirmation_when(true));
assert!(RiskLevel::Sensitive.requires_confirmation_when(true));
let edit = ActionContract {
tags: vec![
ARGUMENT_RISK_TAG.to_owned(),
tilo_action_policy::edits::FIELD_EDIT_TAG.to_owned(),
],
..ActionContract::default()
};
assert_eq!(edit.advertised_confirmation(), ConfirmationPolicy::None);
assert_eq!(
edit.confirmation_for_argument(None),
ConfirmationPolicy::None
);
let phrase = |phrase: &str, kind: ActionKind| ActionContract {
risk: RiskLevel::Destructive,
kind,
confirmation: ConfirmationPolicy::Phrase {
phrase: phrase.into(),
},
..ActionContract::default()
};
assert!(
phrase("Hacker News", ActionKind::Undoable)
.validate_declaration()
.iter()
.any(|error| error.contains("Undo takes back"))
);
for generic in ["CONFIRM", "yes", "Delete"] {
assert!(
phrase(generic, ActionKind::Outside)
.validate_declaration()
.iter()
.any(|error| error.contains("says nothing")),
"{generic}"
);
}
assert!(
phrase("nvme0n1", ActionKind::Outside)
.validate_declaration()
.is_empty()
);
assert!(phrase_is_meaningful("Windows 11"));
assert!(!phrase_is_meaningful(" confirm "));
}
phase an_actions_audience_decides_whose_listings_offer_it;
{
let mut contract = ActionContract::default();
assert_eq!(contract.audience(), Audience::Everyone);
assert!(contract.reaches_people() && contract.reaches_agents());
contract.set_audience(Audience::Agents);
assert_eq!(contract.audience(), Audience::Agents);
assert!(!contract.reaches_people() && contract.reaches_agents());
contract.set_audience(Audience::People);
assert_eq!(contract.audience(), Audience::People);
assert!(contract.reaches_people() && !contract.reaches_agents());
assert_eq!(
contract
.tags
.iter()
.filter(|tag| tag.starts_with("audience:"))
.count(),
1,
"one audience at a time: {:?}",
contract.tags
);
contract.set_audience(Audience::Everyone);
assert!(
contract
.tags
.iter()
.all(|tag| !tag.starts_with("audience:"))
);
}
phase the_contract_keeps_wire_discriminants_and_one_job_identity;
{
risk_level_keeps_existing_compact_wire_discriminants();
broker_owned_job_identity_is_not_a_second_application_result();
}
phase only_a_nullable_json_result_may_be_left_out;
{
let nullable = ResultSpec::Json {
schema: serde_json::json!({"type": ["string", "null"]}),
};
let required = ResultSpec::Json {
schema: serde_json::json!({"type": "string"}),
};
let none = crate::ActionOutput::default();
assert!(nullable.validate(&none).is_ok());
assert!(required.validate(&none).is_err());
let text = crate::ActionOutput {
value: Some(serde_json::json!("changed")),
resources: Vec::new(),
};
assert!(nullable.validate(&text).is_ok());
assert!(required.validate(&text).is_ok());
}
phase offload_is_an_additive_bounded_declaration_on_reads;
{
let local = ActionContract::view();
let json = serde_json::to_value(&local).unwrap();
assert!(json.get("offload").is_none(), "absent stays off the wire");
let old: ActionContract = serde_json::from_value(json).unwrap();
assert_eq!(old.offload, None);
let offload = Offload {
gpu: false,
cpu_time_ms: 60_000,
memory_bytes: 512 * 1024 * 1024,
output_bytes: 8 * 1024 * 1024,
};
let heavy = ActionContract {
offload: Some(offload.clone()),
..ActionContract::view()
};
assert!(heavy.validate_declaration().is_empty());
let round: ActionContract =
serde_json::from_value(serde_json::to_value(&heavy).unwrap()).unwrap();
assert_eq!(round, heavy);
let unbounded = ActionContract {
offload: Some(Offload {
cpu_time_ms: 0,
memory_bytes: MAX_OFFLOAD_MEMORY_BYTES + 1,
output_bytes: MAX_OFFLOAD_OUTPUT_BYTES + 1,
..offload
}),
..ActionContract::view()
};
assert_eq!(unbounded.validate_declaration().len(), 3);
let writes = ActionContract {
offload: Some(offload),
..ActionContract::default()
};
assert_eq!(
writes.validate_declaration(),
vec!["an offloadable action must be a read".to_string()]
);
}
}
}