use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct Intent {
pub id: String,
pub at: u64,
pub verb: String,
pub origin: IntentOrigin,
pub body: IntentBody,
pub body_digest: String,
pub targets: Vec<Target>,
pub analysable: bool,
pub opacity: Option<Opacity>,
pub coverage: Coverage,
pub annotations: IntentAnnotations,
pub reversibility: Reversibility,
pub purpose: Option<String>,
pub lineage: Lineage,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum IntentOrigin {
Cli,
Mcp,
Code,
Poll,
Hook,
Recipe,
Supervisor,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum IntentBody {
Argv {
argv: Vec<String>,
shell: bool,
cwd: Option<String>,
env_keys: Vec<String>,
},
Signal { name: String },
ToolCall {
connector: String,
method: String,
arguments: Value,
},
TypedCall { command_path: String, input: Value },
}
impl IntentBody {
pub fn digest(&self) -> String {
let canonical = canonical_json(&serde_json::to_value(self).unwrap_or(Value::Null));
format!("{:x}", Sha256::digest(canonical.as_bytes()))
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema)]
pub struct Target {
pub kind: TargetKind,
pub key: String,
}
impl Target {
pub fn executable(path: &str) -> Self {
Self {
kind: TargetKind::Executable,
key: format!("exec:{path}"),
}
}
pub fn process(boot_id: &str, pid: u32, started_at_ns: u128) -> Self {
Self {
kind: TargetKind::Process,
key: format!("process:{boot_id}/{pid}/{started_at_ns}"),
}
}
pub fn path(path: &str) -> Self {
Self {
kind: TargetKind::Path,
key: format!("path:{path}"),
}
}
pub fn tool(connector: &str, method: &str) -> Self {
Self {
kind: TargetKind::Tool,
key: format!("tool:{connector}/{method}"),
}
}
pub fn apoc(command_path: &str) -> Self {
Self {
kind: TargetKind::Apoc,
key: format!("apoc:{command_path}"),
}
}
pub fn opaque() -> Self {
Self {
kind: TargetKind::Opaque,
key: "opaque:".to_string(),
}
}
}
#[derive(
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum TargetKind {
Executable,
Process,
Port,
Path,
Tool,
Endpoint,
Apoc,
Opaque,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Opacity {
Shell,
ForeignRuntime,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Coverage {
Precise,
VerbOnly,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct IntentAnnotations {
pub read_only: Option<bool>,
pub destructive: Option<bool>,
pub idempotent: Option<bool>,
pub open_world: Option<bool>,
pub source: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Reversibility {
NoEffect,
Compensable,
Irreversible,
Unknown,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Lineage {
pub actor: Option<String>,
pub invocation_id: Option<String>,
pub execution_id: Option<String>,
pub code_execution_id: Option<String>,
pub code_seq: Option<u64>,
pub session_id: Option<String>,
pub cwd: Option<String>,
pub declaration_id: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Declaration {
pub verbs: Vec<String>,
#[serde(default)]
pub targets: Vec<TargetPattern>,
#[serde(default)]
pub allow_opaque: bool,
#[serde(default)]
pub allow_open_world: bool,
#[serde(default)]
pub max_intents: Option<u32>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "match", content = "key", rename_all = "snake_case")]
pub enum TargetPattern {
Exact(String),
Beneath(String),
}
impl TargetPattern {
fn permits(&self, target: &Target) -> bool {
match self {
TargetPattern::Exact(key) => &target.key == key,
TargetPattern::Beneath(root) => {
let Some(path) = target.key.strip_prefix("path:") else {
return false;
};
let root = root.trim_end_matches('/');
path == root || path.starts_with(&format!("{root}/"))
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "breach", rename_all = "snake_case")]
pub enum Breach {
VerbNotDeclared { verb: String },
TargetNotDeclared { target: String },
OpaqueNotDeclared,
OpenWorldNotDeclared,
TooManyIntents { limit: u32 },
}
impl std::fmt::Display for Breach {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Breach::VerbNotDeclared { verb } => {
write!(formatter, "DECLARATION_BREACH: {verb} was not declared")
}
Breach::TargetNotDeclared { target } => {
write!(formatter, "DECLARATION_BREACH: {target} was not declared")
}
Breach::OpaqueNotDeclared => write!(
formatter,
"DECLARATION_BREACH: an unanalysable request was not declared"
),
Breach::OpenWorldNotDeclared => write!(
formatter,
"DECLARATION_BREACH: an open-world tool was not declared"
),
Breach::TooManyIntents { limit } => write!(
formatter,
"DECLARATION_BREACH: more than the declared {limit} intents"
),
}
}
}
impl Declaration {
pub fn permits(&self, intent: &Intent) -> Result<(), Breach> {
if !self.verbs.iter().any(|verb| verb == &intent.verb) {
return Err(Breach::VerbNotDeclared {
verb: intent.verb.clone(),
});
}
if !intent.analysable && !self.allow_opaque {
return Err(Breach::OpaqueNotDeclared);
}
if intent.annotations.open_world == Some(true) && !self.allow_open_world {
return Err(Breach::OpenWorldNotDeclared);
}
if !self.targets.is_empty() {
for target in &intent.targets {
if target.kind == TargetKind::Opaque {
continue;
}
if !self.targets.iter().any(|pattern| pattern.permits(target)) {
return Err(Breach::TargetNotDeclared {
target: target.key.clone(),
});
}
}
}
Ok(())
}
pub fn permits_plan(&self, intents: &[Intent]) -> Result<(), (usize, Breach)> {
for (index, intent) in intents.iter().enumerate() {
if let Some(limit) = self.max_intents
&& index as u32 >= limit
{
return Err((index, Breach::TooManyIntents { limit }));
}
self.permits(intent).map_err(|breach| (index, breach))?;
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Ruling {
pub intent_id: String,
pub body_digest: String,
pub decision: Decision,
pub reason: String,
pub decider: String,
pub ruled_at: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Decision {
Allow,
Refuse,
Pending,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Decider {
pub name: String,
pub program: String,
#[serde(default)]
pub verbs: Vec<String>,
pub enabled: bool,
pub timeout_ms: u64,
pub on_unavailable: OnUnavailable,
pub created_at: u64,
pub updated_at: u64,
}
impl Decider {
pub fn applies_to(&self, verb: &str) -> bool {
self.enabled && (self.verbs.is_empty() || self.verbs.iter().any(|name| name == verb))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum OnUnavailable {
Allow,
Refuse,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct DeciderAnswer {
pub decider: String,
pub decision: Option<Decision>,
pub reason: String,
pub unavailable: Option<String>,
pub elapsed_ms: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RulingState {
Ruled,
Unchecked,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct IntentRecord {
pub intent: Intent,
pub proceeded: bool,
pub state: RulingState,
pub reason: String,
pub answers: Vec<DeciderAnswer>,
}
pub fn combine(answers: &[DeciderAnswer], deciders: &[Decider]) -> (bool, RulingState, String) {
let mut state = RulingState::Ruled;
let mut refusals = Vec::new();
for answer in answers {
match (&answer.decision, &answer.unavailable) {
(Some(Decision::Refuse), _) => {
refusals.push(format!("{} refused: {}", answer.decider, answer.reason));
}
(Some(Decision::Pending), _) => refusals.push(format!(
"{} left it pending, and a pending ruling cannot yet hold an action open: {}",
answer.decider, answer.reason
)),
(Some(Decision::Allow), _) => {}
(None, unavailable) => {
state = RulingState::Unchecked;
let refuses = deciders
.iter()
.find(|decider| decider.name == answer.decider)
.is_none_or(|decider| decider.on_unavailable == OnUnavailable::Refuse);
if refuses {
refusals.push(format!(
"{} could not answer ({}), and its registrant chose to refuse in that case",
answer.decider,
unavailable.as_deref().unwrap_or("no answer")
));
}
}
}
}
if refusals.is_empty() {
(true, state, String::new())
} else {
(false, state, refusals.join("; "))
}
}
#[async_trait::async_trait]
pub trait IntentGate: Send + Sync {
fn active(&self) -> bool;
async fn offer(&self, intent: Intent) -> Result<(), String>;
}
pub struct Ungated;
#[async_trait::async_trait]
impl IntentGate for Ungated {
fn active(&self) -> bool {
false
}
async fn offer(&self, _intent: Intent) -> Result<(), String> {
Ok(())
}
}
#[allow(clippy::too_many_arguments)]
pub fn for_command(
verb: &str,
argv: &[String],
shell: bool,
cwd: Option<&str>,
env_keys: Vec<String>,
path_var: Option<&str>,
purpose: Option<String>,
lineage: Lineage,
origin: IntentOrigin,
at: u64,
) -> Intent {
let body = IntentBody::Argv {
argv: argv.to_vec(),
shell,
cwd: cwd.map(ToString::to_string),
env_keys,
};
let (targets, analysable, opacity) = if shell {
(vec![Target::opaque()], false, Some(Opacity::Shell))
} else {
let targets = argv
.first()
.and_then(|program| resolve_executable(program, cwd, path_var))
.map(|path| vec![Target::executable(&path)])
.unwrap_or_default();
(targets, true, None)
};
Intent {
id: uuid::Uuid::now_v7().to_string(),
at,
verb: verb.to_string(),
origin,
body_digest: body.digest(),
body,
targets,
analysable,
opacity,
coverage: Coverage::Precise,
annotations: IntentAnnotations {
source: "local".to_string(),
..IntentAnnotations::default()
},
reversibility: Reversibility::Unknown,
purpose,
lineage,
}
}
fn resolve_executable(program: &str, cwd: Option<&str>, path_var: Option<&str>) -> Option<String> {
let is_file = |path: &std::path::Path| path.is_file();
if program.starts_with('/') {
return is_file(std::path::Path::new(program)).then(|| program.to_string());
}
if program.contains('/') {
let joined = std::path::Path::new(cwd?).join(program);
return is_file(&joined).then(|| joined.to_string_lossy().into_owned());
}
path_var?
.split(':')
.filter(|directory| !directory.is_empty())
.map(|directory| std::path::Path::new(directory).join(program))
.find(|candidate| is_file(candidate))
.map(|found| found.to_string_lossy().into_owned())
}
fn canonical_json(value: &Value) -> String {
match value {
Value::Object(map) => {
let mut keys = map.keys().collect::<Vec<_>>();
keys.sort();
let fields = keys
.into_iter()
.map(|key| {
format!(
"{}:{}",
serde_json::to_string(key).unwrap_or_default(),
canonical_json(&map[key])
)
})
.collect::<Vec<_>>();
format!("{{{}}}", fields.join(","))
}
Value::Array(items) => format!(
"[{}]",
items
.iter()
.map(canonical_json)
.collect::<Vec<_>>()
.join(",")
),
other => other.to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn command(argv: &[&str], targets: Vec<Target>) -> Intent {
let body = IntentBody::Argv {
argv: argv.iter().map(|arg| arg.to_string()).collect(),
shell: false,
cwd: None,
env_keys: Vec::new(),
};
Intent {
id: "intent".into(),
at: 1,
verb: "execution.command".into(),
origin: IntentOrigin::Cli,
body_digest: body.digest(),
body,
targets,
analysable: true,
opacity: None,
coverage: Coverage::Precise,
annotations: IntentAnnotations::default(),
reversibility: Reversibility::Unknown,
purpose: None,
lineage: Lineage::default(),
}
}
fn shell(script: &str) -> Intent {
let mut intent = command(&[script], vec![Target::opaque()]);
intent.body = IntentBody::Argv {
argv: vec![script.into()],
shell: true,
cwd: None,
env_keys: Vec::new(),
};
intent.body_digest = intent.body.digest();
intent.analysable = false;
intent.opacity = Some(Opacity::Shell);
intent
}
fn decider(name: &str, on_unavailable: OnUnavailable) -> Decider {
Decider {
name: name.into(),
program: "return {decision: 'allow'};".into(),
verbs: Vec::new(),
enabled: true,
timeout_ms: 2_000,
on_unavailable,
created_at: 1,
updated_at: 1,
}
}
fn answer(
decider: &str,
decision: Option<Decision>,
unavailable: Option<&str>,
) -> DeciderAnswer {
DeciderAnswer {
decider: decider.into(),
decision,
reason: "because".into(),
unavailable: unavailable.map(ToString::to_string),
elapsed_ms: 1,
}
}
#[test]
fn one_refusal_refuses_and_names_who_refused() {
let deciders = [
decider("a", OnUnavailable::Allow),
decider("b", OnUnavailable::Allow),
];
let (proceeded, state, reason) = combine(
&[
answer("a", Some(Decision::Allow), None),
answer("b", Some(Decision::Refuse), None),
],
&deciders,
);
assert!(!proceeded);
assert_eq!(state, RulingState::Ruled);
assert!(reason.starts_with("b refused: because"), "{reason}");
}
#[test]
fn an_unavailable_decider_follows_its_registrants_choice_and_is_never_a_ruling() {
for (choice, proceeds) in [(OnUnavailable::Allow, true), (OnUnavailable::Refuse, false)] {
let deciders = [decider("slow", choice)];
let (proceeded, state, _) = combine(
&[answer("slow", None, Some("timed out after 2000 ms"))],
&deciders,
);
assert_eq!(proceeded, proceeds, "{choice:?}");
assert_eq!(state, RulingState::Unchecked, "{choice:?}");
}
}
#[test]
fn a_pending_answer_refuses_until_actions_can_be_held_open() {
let (proceeded, _, reason) = combine(
&[answer("a", Some(Decision::Pending), None)],
&[decider("a", OnUnavailable::Allow)],
);
assert!(!proceeded);
assert!(reason.contains("pending"), "{reason}");
}
#[test]
fn a_command_names_only_the_executable_it_resolves() {
let intent = for_command(
"execution.command",
&["rm".into(), "-rf".into(), "$TMPDIR/x".into()],
false,
Some("/"),
Vec::new(),
Some("/nonexistent:/bin"),
None,
Lineage::default(),
IntentOrigin::Cli,
1,
);
assert_eq!(intent.targets, vec![Target::executable("/bin/rm")]);
assert!(intent.analysable);
let unresolvable = for_command(
"execution.command",
&["no-such-program-anywhere".into()],
false,
None,
Vec::new(),
Some("/bin"),
None,
Lineage::default(),
IntentOrigin::Cli,
1,
);
assert!(unresolvable.targets.is_empty());
let shell = for_command(
"execution.command",
&["rm -rf $TMPDIR/x".into()],
true,
None,
Vec::new(),
Some("/bin"),
None,
Lineage::default(),
IntentOrigin::Cli,
1,
);
assert_eq!(shell.targets, vec![Target::opaque()]);
assert!(!shell.analysable);
assert_eq!(shell.opacity, Some(Opacity::Shell));
}
#[test]
fn a_body_digest_ignores_field_order_but_not_content() {
let a = IntentBody::ToolCall {
connector: "github".into(),
method: "create_issue".into(),
arguments: serde_json::json!({"title": "x", "body": "y"}),
};
let b = IntentBody::ToolCall {
connector: "github".into(),
method: "create_issue".into(),
arguments: serde_json::json!({"body": "y", "title": "x"}),
};
let c = IntentBody::ToolCall {
connector: "github".into(),
method: "create_issue".into(),
arguments: serde_json::json!({"body": "z", "title": "x"}),
};
assert_eq!(a.digest(), b.digest());
assert_ne!(a.digest(), c.digest());
}
#[test]
fn an_undeclared_verb_is_a_breach() {
let declaration = Declaration {
verbs: vec!["process.signal".into()],
..Declaration::default()
};
let intent = command(&["/bin/ls"], vec![Target::executable("/bin/ls")]);
assert_eq!(
declaration.permits(&intent),
Err(Breach::VerbNotDeclared {
verb: "execution.command".into()
})
);
}
#[test]
fn a_shell_string_needs_opacity_declared() {
let mut declaration = Declaration {
verbs: vec!["execution.command".into()],
..Declaration::default()
};
assert_eq!(
declaration.permits(&shell("rm -rf $TMPDIR/x")),
Err(Breach::OpaqueNotDeclared)
);
declaration.allow_opaque = true;
assert_eq!(declaration.permits(&shell("rm -rf $TMPDIR/x")), Ok(()));
}
#[test]
fn declared_targets_bound_what_a_command_may_touch() {
let declaration = Declaration {
verbs: vec!["execution.command".into()],
targets: vec![
TargetPattern::Exact("exec:/bin/echo".into()),
TargetPattern::Beneath("/work".into()),
],
..Declaration::default()
};
let echo = command(
&["/bin/echo"],
vec![Target::executable("/bin/echo"), Target::path("/work/a")],
);
assert_eq!(declaration.permits(&echo), Ok(()));
let ls = command(&["/bin/ls"], vec![Target::executable("/bin/ls")]);
assert_eq!(
declaration.permits(&ls),
Err(Breach::TargetNotDeclared {
target: "exec:/bin/ls".into()
})
);
let sibling = command(
&["/bin/echo"],
vec![Target::executable("/bin/echo"), Target::path("/workshop")],
);
assert_eq!(
declaration.permits(&sibling),
Err(Breach::TargetNotDeclared {
target: "path:/workshop".into()
})
);
}
#[test]
fn an_open_world_tool_needs_it_declared() {
let mut intent = command(&["/bin/echo"], Vec::new());
intent.annotations.open_world = Some(true);
let declaration = Declaration {
verbs: vec!["execution.command".into()],
..Declaration::default()
};
assert_eq!(
declaration.permits(&intent),
Err(Breach::OpenWorldNotDeclared)
);
}
#[test]
fn a_plan_is_bounded_by_its_declared_size() {
let declaration = Declaration {
verbs: vec!["execution.command".into()],
max_intents: Some(2),
..Declaration::default()
};
let one = command(&["/bin/echo"], Vec::new());
assert_eq!(
declaration.permits_plan(&[one.clone(), one.clone()]),
Ok(())
);
assert_eq!(
declaration.permits_plan(&[one.clone(), one.clone(), one]),
Err((2, Breach::TooManyIntents { limit: 2 }))
);
}
#[test]
fn whole_plan_and_per_action_checks_agree_on_every_intent() {
let verbs = ["execution.command", "process.signal"];
let target_sets: Vec<Vec<Target>> = vec![
vec![],
vec![Target::executable("/bin/echo")],
vec![Target::executable("/bin/ls")],
vec![Target::path("/work/a")],
vec![Target::path("/workshop")],
vec![Target::opaque()],
];
let declarations = [
Declaration::default(),
Declaration {
verbs: vec!["execution.command".into()],
..Declaration::default()
},
Declaration {
verbs: vec!["execution.command".into()],
targets: vec![
TargetPattern::Exact("exec:/bin/echo".into()),
TargetPattern::Beneath("/work".into()),
],
allow_opaque: true,
..Declaration::default()
},
Declaration {
verbs: verbs.iter().map(|verb| verb.to_string()).collect(),
allow_open_world: true,
..Declaration::default()
},
];
let mut checked = 0;
for declaration in &declarations {
for verb in verbs {
for targets in &target_sets {
for (analysable, open_world) in
[(true, None), (false, None), (true, Some(true))]
{
let mut intent = command(&["/bin/echo"], targets.clone());
intent.verb = verb.to_string();
intent.analysable = analysable;
intent.annotations.open_world = open_world;
let per_action = declaration.permits(&intent);
let whole_plan = declaration
.permits_plan(std::slice::from_ref(&intent))
.map_err(|(_, breach)| breach);
assert_eq!(per_action, whole_plan, "{declaration:?} {intent:?}");
checked += 1;
}
}
}
}
assert_eq!(checked, 4 * 2 * 6 * 3);
}
}