use serde_json::{Value, json};
use crate::model::SessionId;
const ENVELOPE_KEY: &str = "kian";
const CONTROL_TYPE: &str = "control";
const INTERRUPT_ACTION: &str = "interrupt";
const CONFIRM_ACTION: &str = "confirm";
const EFFECT_ASSUMPTION_ACTION: &str = "effect-assumption";
const BUDGET_ACTION: &str = "budget";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InterruptIntent {
pub reason: Option<String>,
pub requested_by: Option<String>,
pub requested_at_ms: u64,
pub target_epoch: Option<u64>,
pub terminal: bool,
pub cause: Option<String>,
}
impl InterruptIntent {
pub const JOB_CHILD_CANCEL: &'static str = "job_child_cancel";
#[must_use]
pub fn is_control_envelope(payload: &Value) -> bool {
Self::parse(payload).is_some()
}
#[must_use]
pub fn parse(payload: &Value) -> Option<Self> {
let obj = payload.as_object()?;
if obj.len() != 1 {
return None;
}
let inner = obj.get(ENVELOPE_KEY)?.as_object()?;
if inner.get("type").and_then(Value::as_str) != Some(CONTROL_TYPE)
|| inner.get("action").and_then(Value::as_str) != Some(INTERRUPT_ACTION)
{
return None;
}
let terminal = match inner.get("terminal") {
None => false,
Some(value) => value.as_bool()?,
};
let has_cause = inner.contains_key("cause");
let cause = inner.get("cause").and_then(Value::as_str);
let cause = match (terminal, has_cause, cause) {
(false, false, None) => None,
(true, true, Some(Self::JOB_CHILD_CANCEL)) => Some(Self::JOB_CHILD_CANCEL.to_string()),
_ => return None,
};
Some(Self {
reason: inner
.get("reason")
.and_then(Value::as_str)
.map(str::to_owned),
requested_by: inner
.get("requested_by")
.and_then(Value::as_str)
.map(str::to_owned),
requested_at_ms: inner
.get("requested_at_ms")
.and_then(Value::as_u64)
.unwrap_or(0),
target_epoch: inner.get("target_epoch").and_then(Value::as_u64),
terminal,
cause,
})
}
pub fn validate(&self) -> Result<(), String> {
match (self.terminal, self.cause.as_deref()) {
(false, None) => Ok(()),
(true, Some(Self::JOB_CHILD_CANCEL)) => Ok(()),
(true, Some(cause)) => Err(format!("unknown terminal interrupt cause `{cause}`")),
(true, None) => Err("terminal interrupt requires cause `job_child_cancel`".to_string()),
(false, Some(_)) => Err("interrupt cause requires terminal:true".to_string()),
}
}
#[must_use]
pub fn envelope(&self) -> Value {
let mut inner = json!({
"type": CONTROL_TYPE,
"action": INTERRUPT_ACTION,
"requested_at_ms": self.requested_at_ms,
});
let map = inner.as_object_mut().expect("literal object");
match &self.reason {
Some(r) => map.insert("reason".into(), json!(r)),
None => map.insert("reason".into(), Value::Null),
};
match &self.requested_by {
Some(r) => map.insert("requested_by".into(), json!(r)),
None => map.insert("requested_by".into(), Value::Null),
};
map.insert(
"target_epoch".into(),
self.target_epoch.map_or(Value::Null, |e| json!(e)),
);
if self.terminal {
map.insert("terminal".into(), json!(true));
map.insert(
"cause".into(),
self.cause
.as_ref()
.map_or(Value::Null, |cause| json!(cause)),
);
}
json!({ ENVELOPE_KEY: inner })
}
#[must_use]
pub fn event_payload(&self, stale: bool) -> Value {
let mut payload = json!({
"action": INTERRUPT_ACTION,
"requested_at_ms": self.requested_at_ms,
});
let map = payload.as_object_mut().expect("literal object");
match &self.reason {
Some(r) => map.insert("reason".into(), json!(r)),
None => map.insert("reason".into(), Value::Null),
};
match &self.requested_by {
Some(r) => map.insert("requested_by".into(), json!(r)),
None => map.insert("requested_by".into(), Value::Null),
};
map.insert(
"target_epoch".into(),
self.target_epoch.map_or(Value::Null, |e| json!(e)),
);
if self.terminal {
map.insert("terminal".into(), json!(true));
map.insert(
"cause".into(),
self.cause
.as_ref()
.map_or(Value::Null, |cause| json!(cause)),
);
}
if stale {
map.insert("stale".into(), json!(true));
}
payload
}
#[must_use]
pub fn idempotency_key(session: &SessionId, target_epoch: Option<u64>) -> String {
match target_epoch {
Some(e) => format!("interrupt:{}:{}", session.0, e),
None => format!("interrupt:{}:null", session.0),
}
}
#[must_use]
pub fn job_child_cancel_idempotency_key(
run: &str,
step: &str,
attempt: u32,
target_epoch: Option<u64>,
) -> String {
match target_epoch {
Some(epoch) => {
format!("kian:job:child-cancel:{run}:{step}:{attempt}:{epoch}")
}
None => format!("kian:job:child-cancel:{run}:{step}:{attempt}:null"),
}
}
}
#[must_use]
pub fn is_reserved_control_shape(payload: &Value) -> bool {
let Some(obj) = payload.as_object() else {
return false;
};
if obj.len() != 1 {
return false;
}
let Some(inner) = obj.get(ENVELOPE_KEY).and_then(Value::as_object) else {
return false;
};
inner.get("type").and_then(Value::as_str) == Some(CONTROL_TYPE)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfirmIntent {
pub call_id: String,
pub decision: ConfirmDecision,
pub reason: Option<String>,
pub requested_by: Option<String>,
pub answered_at_ms: u64,
pub expired: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfirmDecision {
Approve,
Reject,
}
impl ConfirmDecision {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Approve => "approve",
Self::Reject => "reject",
}
}
#[must_use]
pub fn parse(s: &str) -> Option<Self> {
match s {
"approve" => Some(Self::Approve),
"reject" => Some(Self::Reject),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EffectAssumption {
NoEffect,
}
impl EffectAssumption {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::NoEffect => "no_effect",
}
}
#[must_use]
pub fn parse(raw: &str) -> Option<Self> {
match raw {
"no_effect" => Some(Self::NoEffect),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EffectAssumptionIntent {
pub run: SessionId,
pub step: String,
pub prior_attempt: u32,
pub assumed: EffectAssumption,
pub reason: String,
pub requested_by: Option<String>,
pub requested_at_ms: u64,
}
impl EffectAssumptionIntent {
#[must_use]
pub fn is_action(payload: &Value) -> bool {
payload
.as_object()
.filter(|obj| obj.len() == 1)
.and_then(|obj| obj.get(ENVELOPE_KEY))
.and_then(Value::as_object)
.is_some_and(|inner| {
inner.get("type").and_then(Value::as_str) == Some(CONTROL_TYPE)
&& inner.get("action").and_then(Value::as_str) == Some(EFFECT_ASSUMPTION_ACTION)
})
}
pub fn parse(payload: &Value) -> Result<Option<Self>, String> {
if !Self::is_action(payload) {
return Ok(None);
}
let inner = payload
.get(ENVELOPE_KEY)
.and_then(Value::as_object)
.expect("is_action checked the envelope");
Self::parse_inner(inner, true).map(Some)
}
pub fn from_event_payload(payload: &Value) -> Result<Option<Self>, String> {
let Some(inner) = payload.as_object() else {
return Ok(None);
};
if inner.get("action").and_then(Value::as_str) != Some(EFFECT_ASSUMPTION_ACTION) {
return Ok(None);
}
Self::parse_inner(inner, false).map(Some)
}
fn parse_inner(inner: &serde_json::Map<String, Value>, envelope: bool) -> Result<Self, String> {
let allowed = [
"type",
"action",
"run",
"step",
"prior_attempt",
"assumed",
"reason",
"requested_by",
"requested_at_ms",
];
if inner.keys().any(|key| !allowed.contains(&key.as_str())) {
return Err("effect-assumption payload carries an unknown key".to_string());
}
let required = [
"action",
"run",
"step",
"prior_attempt",
"assumed",
"reason",
"requested_at_ms",
];
if required.iter().any(|key| !inner.contains_key(*key)) {
return Err("effect-assumption payload is missing a required key".to_string());
}
if envelope
&& (inner.get("type").and_then(Value::as_str) != Some(CONTROL_TYPE)
|| inner.get("action").and_then(Value::as_str) != Some(EFFECT_ASSUMPTION_ACTION))
{
return Err("effect-assumption envelope has invalid discriminators".to_string());
}
if !envelope && inner.get("type").is_some() {
return Err("effect-assumption event payload carries the row envelope".to_string());
}
let run = inner
.get("run")
.and_then(Value::as_str)
.and_then(|raw| uuid::Uuid::parse_str(raw).ok())
.map(SessionId)
.ok_or_else(|| "effect-assumption run is not a canonical session id".to_string())?;
let step = inner
.get("step")
.and_then(Value::as_str)
.filter(|step| !step.trim().is_empty())
.map(str::to_owned)
.ok_or_else(|| "effect-assumption step is empty".to_string())?;
let prior_attempt = inner
.get("prior_attempt")
.and_then(Value::as_u64)
.and_then(|attempt| u32::try_from(attempt).ok())
.filter(|attempt| *attempt > 0)
.ok_or_else(|| {
"effect-assumption prior_attempt is not a positive attempt".to_string()
})?;
let assumed = inner
.get("assumed")
.and_then(Value::as_str)
.and_then(EffectAssumption::parse)
.ok_or_else(|| "effect-assumption assumed value is not `no_effect`".to_string())?;
let reason = inner
.get("reason")
.and_then(Value::as_str)
.filter(|reason| !reason.trim().is_empty())
.map(str::to_owned)
.ok_or_else(|| "effect-assumption reason is empty".to_string())?;
let requested_by = match inner.get("requested_by") {
None => None,
Some(Value::String(value)) if !value.trim().is_empty() => Some(value.clone()),
Some(_) => {
return Err(
"effect-assumption requested_by must be a non-empty string when present"
.to_string(),
);
}
};
let requested_at_ms = inner
.get("requested_at_ms")
.and_then(Value::as_u64)
.ok_or_else(|| "effect-assumption requested_at_ms is not a u64".to_string())?;
Ok(Self {
run,
step,
prior_attempt,
assumed,
reason,
requested_by,
requested_at_ms,
})
}
#[must_use]
pub fn envelope(&self) -> Value {
let mut inner = self.payload_inner();
inner.insert("type".into(), json!(CONTROL_TYPE));
json!({ ENVELOPE_KEY: Value::Object(inner) })
}
#[must_use]
pub fn event_payload(&self) -> Value {
Value::Object(self.payload_inner())
}
fn payload_inner(&self) -> serde_json::Map<String, Value> {
let mut inner = serde_json::Map::new();
inner.insert("action".into(), json!(EFFECT_ASSUMPTION_ACTION));
inner.insert("run".into(), json!(self.run.0.to_string()));
inner.insert("step".into(), json!(self.step));
inner.insert("prior_attempt".into(), json!(self.prior_attempt));
inner.insert("assumed".into(), json!(self.assumed.as_str()));
inner.insert("reason".into(), json!(self.reason));
if let Some(requested_by) = &self.requested_by {
inner.insert("requested_by".into(), json!(requested_by));
}
inner.insert("requested_at_ms".into(), json!(self.requested_at_ms));
inner
}
#[must_use]
pub fn idempotency_key(run: &SessionId, step: &str, prior_attempt: u32) -> String {
format!("effect-assumption:{}:{step}:{prior_attempt}", run.0)
}
}
impl ConfirmIntent {
#[must_use]
pub fn is_control_envelope(payload: &Value) -> bool {
Self::parse(payload).is_some()
}
#[must_use]
pub fn is_reserved_shape(payload: &Value) -> bool {
is_reserved_control_shape(payload)
}
#[must_use]
pub fn parse(payload: &Value) -> Option<Self> {
let obj = payload.as_object()?;
if obj.len() != 1 {
return None;
}
let inner = obj.get(ENVELOPE_KEY)?.as_object()?;
if inner.get("type").and_then(Value::as_str) != Some(CONTROL_TYPE)
|| inner.get("action").and_then(Value::as_str) != Some(CONFIRM_ACTION)
{
return None;
}
let call_id = inner
.get("call_id")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())?
.to_owned();
let decision = inner
.get("decision")
.and_then(Value::as_str)
.and_then(ConfirmDecision::parse)?;
Some(Self {
call_id,
decision,
reason: inner
.get("reason")
.and_then(Value::as_str)
.map(str::to_owned),
requested_by: inner
.get("requested_by")
.and_then(Value::as_str)
.map(str::to_owned),
answered_at_ms: inner
.get("answered_at_ms")
.and_then(Value::as_u64)
.unwrap_or(0),
expired: inner.get("expired").and_then(Value::as_bool) == Some(true),
})
}
#[must_use]
pub fn from_event_payload(payload: &Value) -> Option<Self> {
let inner = payload.as_object()?;
if inner.get("action").and_then(Value::as_str) != Some(CONFIRM_ACTION) {
return None;
}
let call_id = inner
.get("call_id")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())?
.to_owned();
let decision = inner
.get("decision")
.and_then(Value::as_str)
.and_then(ConfirmDecision::parse)?;
Some(Self {
call_id,
decision,
reason: inner
.get("reason")
.and_then(Value::as_str)
.map(str::to_owned),
requested_by: inner
.get("requested_by")
.and_then(Value::as_str)
.map(str::to_owned),
answered_at_ms: inner
.get("answered_at_ms")
.and_then(Value::as_u64)
.unwrap_or(0),
expired: inner.get("expired").and_then(Value::as_bool) == Some(true),
})
}
#[must_use]
pub fn envelope(&self) -> Value {
let mut inner = json!({
"type": CONTROL_TYPE,
"action": CONFIRM_ACTION,
"call_id": self.call_id,
"decision": self.decision.as_str(),
"reason": self.reason,
"requested_by": self.requested_by,
"answered_at_ms": self.answered_at_ms,
});
if self.expired {
inner["expired"] = json!(true);
}
json!({ ENVELOPE_KEY: inner })
}
#[must_use]
pub fn event_payload(&self) -> Value {
let mut payload = json!({
"action": CONFIRM_ACTION,
"call_id": self.call_id,
"decision": self.decision.as_str(),
"reason": self.reason,
"requested_by": self.requested_by,
"answered_at_ms": self.answered_at_ms,
});
if self.expired {
payload["expired"] = json!(true);
}
payload
}
#[must_use]
pub fn idempotency_key(session: &SessionId, call_id: &str) -> String {
format!("confirm:{}:{}", session.0, call_id)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BudgetIntent {
pub tokens: Option<u64>,
pub wall_clock_ms: Option<u64>,
pub reason: Option<String>,
pub requested_by: Option<String>,
pub requested_at_ms: u64,
}
impl BudgetIntent {
#[must_use]
pub fn is_control_envelope(payload: &Value) -> bool {
Self::parse(payload).is_some()
}
#[must_use]
pub fn parse(payload: &Value) -> Option<Self> {
let obj = payload.as_object()?;
if obj.len() != 1 {
return None;
}
let inner = obj.get(ENVELOPE_KEY)?.as_object()?;
if inner.get("type").and_then(Value::as_str) != Some(CONTROL_TYPE)
|| inner.get("action").and_then(Value::as_str) != Some(BUDGET_ACTION)
{
return None;
}
Some(Self {
tokens: inner.get("tokens").and_then(Value::as_u64),
wall_clock_ms: inner.get("wall_clock_ms").and_then(Value::as_u64),
reason: inner
.get("reason")
.and_then(Value::as_str)
.map(str::to_owned),
requested_by: inner
.get("requested_by")
.and_then(Value::as_str)
.map(str::to_owned),
requested_at_ms: inner
.get("requested_at_ms")
.and_then(Value::as_u64)
.unwrap_or(0),
})
}
#[must_use]
pub fn envelope(&self) -> Value {
let mut inner = json!({
"type": CONTROL_TYPE,
"action": BUDGET_ACTION,
"requested_at_ms": self.requested_at_ms,
});
let map = inner.as_object_mut().expect("literal object");
map.insert(
"tokens".into(),
self.tokens.map_or(Value::Null, |tokens| json!(tokens)),
);
map.insert(
"wall_clock_ms".into(),
self.wall_clock_ms.map_or(Value::Null, |ms| json!(ms)),
);
map.insert(
"reason".into(),
self.reason
.as_ref()
.map_or(Value::Null, |reason| json!(reason)),
);
map.insert(
"requested_by".into(),
self.requested_by
.as_ref()
.map_or(Value::Null, |by| json!(by)),
);
json!({ ENVELOPE_KEY: inner })
}
#[must_use]
pub fn event_payload(&self) -> Value {
let mut payload = json!({
"action": BUDGET_ACTION,
"requested_at_ms": self.requested_at_ms,
});
let map = payload.as_object_mut().expect("literal object");
if let Some(tokens) = self.tokens {
map.insert("tokens".into(), json!(tokens));
}
if let Some(ms) = self.wall_clock_ms {
map.insert("wall_clock_ms".into(), json!(ms));
}
map.insert(
"reason".into(),
self.reason
.as_ref()
.map_or(Value::Null, |reason| json!(reason)),
);
map.insert(
"requested_by".into(),
self.requested_by
.as_ref()
.map_or(Value::Null, |by| json!(by)),
);
payload
}
#[must_use]
pub fn idempotency_key(
session: &SessionId,
tokens: Option<u64>,
wall_clock_ms: Option<u64>,
requested_at_ms: u64,
) -> String {
format!(
"budget:{}:{}:{}:{}",
session.0,
tokens.unwrap_or(0),
wall_clock_ms.unwrap_or(0),
requested_at_ms
)
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use uuid::Uuid;
use super::{
BudgetIntent, ConfirmDecision, ConfirmIntent, EffectAssumption, EffectAssumptionIntent,
InterruptIntent,
};
use crate::model::SessionId;
fn intent() -> InterruptIntent {
InterruptIntent {
reason: Some("stop the deploy".into()),
requested_by: Some("replica-a".into()),
requested_at_ms: 1_762_000_000_000,
target_epoch: Some(3),
terminal: false,
cause: None,
}
}
#[test]
fn envelope_round_trips_through_parse() {
let i = intent();
let envelope = i.envelope();
assert_eq!(
envelope,
json!({
"kian": {
"type": "control",
"action": "interrupt",
"reason": "stop the deploy",
"requested_by": "replica-a",
"requested_at_ms": 1_762_000_000_000_u64,
"target_epoch": 3
}
})
);
assert_eq!(InterruptIntent::parse(&envelope), Some(i));
assert!(InterruptIntent::is_control_envelope(&envelope));
}
#[test]
fn null_fields_round_trip() {
let i = InterruptIntent {
reason: None,
requested_by: None,
requested_at_ms: 7,
target_epoch: None,
terminal: false,
cause: None,
};
assert_eq!(InterruptIntent::parse(&i.envelope()), Some(i));
}
#[test]
fn minimal_envelope_parses_with_defaults() {
let minimal = json!({"kian": {"type": "control", "action": "interrupt"}});
assert_eq!(
InterruptIntent::parse(&minimal),
Some(InterruptIntent {
reason: None,
requested_by: None,
requested_at_ms: 0,
target_epoch: None,
terminal: false,
cause: None,
})
);
}
#[test]
fn only_the_exact_reserved_shape_is_an_envelope() {
for payload in [
json!({"kian": {"type": "control", "action": "interrupt"}, "extra": 1}),
json!({"kian": {"type": "user", "action": "interrupt"}}),
json!({"kian": {"type": "control", "action": "cancel"}}),
json!({"kian": "not an object"}),
json!({"synthetic": true, "content": "steer"}),
json!({"content": "x", "spill": "y"}),
json!("plain string"),
json!({"role": "user", "content": "hi"}),
] {
assert!(
!InterruptIntent::is_control_envelope(&payload),
"{payload} must be plain content"
);
}
}
#[test]
fn event_payload_shape_and_stale_marker() {
let live = intent().event_payload(false);
assert_eq!(
live,
json!({
"action": "interrupt",
"reason": "stop the deploy",
"requested_by": "replica-a",
"requested_at_ms": 1_762_000_000_000_u64,
"target_epoch": 3
})
);
assert!(live.get("stale").is_none());
let stale = intent().event_payload(true);
assert_eq!(stale.get("stale"), Some(&json!(true)));
let mut without = stale.clone();
without.as_object_mut().unwrap().remove("stale");
assert_eq!(without, live);
}
#[test]
fn idempotency_key_is_deterministic() {
let sid = SessionId(Uuid::nil());
assert_eq!(
InterruptIntent::idempotency_key(&sid, Some(3)),
format!("interrupt:{}:3", sid.0)
);
assert_eq!(
InterruptIntent::idempotency_key(&sid, None),
format!("interrupt:{}:null", sid.0)
);
assert_eq!(
InterruptIntent::job_child_cancel_idempotency_key(
"digest@manual:T1",
"fetch",
2,
Some(9),
),
"kian:job:child-cancel:digest@manual:T1:fetch:2:9"
);
assert_ne!(
InterruptIntent::job_child_cancel_idempotency_key(
"digest@manual:T1",
"fetch",
2,
Some(9),
),
InterruptIntent::idempotency_key(&sid, Some(9))
);
}
#[test]
fn terminal_job_child_cancel_round_trips_and_keeps_legacy_bytes() {
let legacy = intent();
assert!(legacy.envelope()["kian"].get("terminal").is_none());
assert!(legacy.envelope()["kian"].get("cause").is_none());
assert!(legacy.event_payload(false).get("terminal").is_none());
assert!(legacy.event_payload(false).get("cause").is_none());
let terminal = InterruptIntent {
reason: Some("step timed out".into()),
requested_by: Some("job:digest@manual:T1:fetch:1".into()),
requested_at_ms: 17,
target_epoch: Some(4),
terminal: true,
cause: Some(InterruptIntent::JOB_CHILD_CANCEL.to_string()),
};
assert_eq!(terminal.validate(), Ok(()));
assert_eq!(
terminal.envelope()["kian"],
json!({
"type": "control",
"action": "interrupt",
"reason": "step timed out",
"requested_by": "job:digest@manual:T1:fetch:1",
"requested_at_ms": 17,
"target_epoch": 4,
"terminal": true,
"cause": "job_child_cancel"
})
);
assert_eq!(
InterruptIntent::parse(&terminal.envelope()),
Some(terminal.clone())
);
assert_eq!(
InterruptIntent::parse(&json!({
"kian": {
"type": "control",
"action": "interrupt",
"terminal": true,
"cause": "unknown"
}
})),
None
);
assert_eq!(
InterruptIntent::parse(&json!({
"kian": {
"type": "control",
"action": "interrupt",
"terminal": false,
"cause": null
}
})),
None
);
assert_eq!(
InterruptIntent::parse(&json!({
"kian": {
"type": "control",
"action": "interrupt",
"cause": "job_child_cancel"
}
})),
None
);
assert_eq!(
InterruptIntent::parse(&json!({
"kian": {
"type": "control",
"action": "interrupt",
"terminal": false,
"cause": "job_child_cancel"
}
})),
None
);
assert_eq!(
InterruptIntent::parse(&json!({
"kian": {
"type": "control",
"action": "interrupt",
"terminal": true
}
})),
None
);
let bad = InterruptIntent {
terminal: true,
cause: None,
..terminal.clone()
};
assert!(bad.validate().is_err());
let bad = InterruptIntent {
terminal: false,
cause: Some(InterruptIntent::JOB_CHILD_CANCEL.to_string()),
..terminal
};
assert!(bad.validate().is_err());
}
#[test]
fn confirm_envelope_round_trips_and_reserved_shape_covers_both_actions() {
let i = ConfirmIntent {
call_id: "call-1".into(),
decision: ConfirmDecision::Approve,
reason: Some("looks right".into()),
requested_by: Some("alice".into()),
answered_at_ms: 1_762_000_000_000,
expired: false,
};
let envelope = i.envelope();
assert_eq!(
envelope,
json!({"kian": {"type": "control", "action": "confirm", "call_id": "call-1",
"decision": "approve", "reason": "looks right",
"requested_by": "alice", "answered_at_ms": 1_762_000_000_000_u64}})
);
assert_eq!(ConfirmIntent::parse(&envelope), Some(i));
assert!(ConfirmIntent::is_control_envelope(&envelope));
assert!(ConfirmIntent::is_reserved_shape(&envelope));
let expired = ConfirmIntent {
expired: true,
decision: ConfirmDecision::Reject,
reason: None,
requested_by: None,
answered_at_ms: 5,
call_id: "call-2".into(),
};
assert_eq!(
ConfirmIntent::parse(&expired.envelope()),
Some(expired.clone())
);
assert_eq!(expired.event_payload()["expired"], json!(true));
assert_eq!(expired.event_payload()["decision"], json!("reject"));
let interrupt = InterruptIntent {
reason: None,
requested_by: None,
requested_at_ms: 1,
target_epoch: None,
terminal: false,
cause: None,
}
.envelope();
assert!(ConfirmIntent::is_reserved_shape(&interrupt));
assert!(!ConfirmIntent::is_control_envelope(&interrupt));
for plain in [
json!({"kian": {"type": "control", "action": "confirm"}}),
json!({"kian": {"type": "control", "action": "confirm", "call_id": "c",
"decision": "maybe"}}),
json!({"kian": {"type": "async_result", "job_id": "j"}}),
json!({"kian": {"type": "control", "action": "confirm"}, "extra": 1}),
json!({"kian": "string"}),
] {
assert!(!ConfirmIntent::is_control_envelope(&plain), "{plain}");
}
assert!(!ConfirmIntent::is_reserved_shape(
&json!({"kian": {"type": "async_result"}})
));
assert!(!ConfirmIntent::is_reserved_shape(&json!("plain")));
}
#[test]
fn confirm_idempotency_key_is_deterministic() {
let sid = SessionId(Uuid::nil());
assert_eq!(
ConfirmIntent::idempotency_key(&sid, "call-1"),
format!("confirm:{}:call-1", sid.0)
);
}
#[test]
fn effect_assumption_round_trips_with_the_exact_additive_payload() {
let run = SessionId(Uuid::from_u128(7));
let intent = EffectAssumptionIntent {
run,
step: "publish".into(),
prior_attempt: 2,
assumed: EffectAssumption::NoEffect,
reason: "checked the remote branch".into(),
requested_by: Some("alice".into()),
requested_at_ms: 1_762_000_000_123,
};
assert_eq!(
intent.envelope(),
json!({
"kian": {
"type": "control",
"action": "effect-assumption",
"run": run.0.to_string(),
"step": "publish",
"prior_attempt": 2,
"assumed": "no_effect",
"reason": "checked the remote branch",
"requested_by": "alice",
"requested_at_ms": 1_762_000_000_123_u64
}
})
);
assert_eq!(
intent.event_payload(),
json!({
"action": "effect-assumption",
"run": run.0.to_string(),
"step": "publish",
"prior_attempt": 2,
"assumed": "no_effect",
"reason": "checked the remote branch",
"requested_by": "alice",
"requested_at_ms": 1_762_000_000_123_u64
})
);
assert_eq!(
EffectAssumptionIntent::parse(&intent.envelope()),
Ok(Some(intent.clone()))
);
assert_eq!(
EffectAssumptionIntent::from_event_payload(&intent.event_payload()),
Ok(Some(intent.clone()))
);
assert_eq!(
EffectAssumptionIntent::idempotency_key(&run, "publish", 2),
format!("effect-assumption:{}:publish:2", run.0)
);
let without_requester = EffectAssumptionIntent {
requested_by: None,
..intent
};
assert!(
without_requester
.event_payload()
.get("requested_by")
.is_none()
);
assert_eq!(
EffectAssumptionIntent::parse(&without_requester.envelope()),
Ok(Some(without_requester))
);
}
#[test]
fn malformed_effect_assumptions_are_refused_not_plain_content() {
let run = Uuid::nil().to_string();
let valid = json!({
"kian": {
"type": "control",
"action": "effect-assumption",
"run": run,
"step": "publish",
"prior_attempt": 1,
"assumed": "no_effect",
"reason": "checked",
"requested_at_ms": 1
}
});
assert!(EffectAssumptionIntent::parse(&valid).unwrap().is_some());
for malformed in [
json!({"kian": {"type": "control", "action": "effect-assumption"}}),
json!({
"kian": {
"type": "control",
"action": "effect-assumption",
"run": "not-a-session",
"step": "publish",
"prior_attempt": 1,
"assumed": "no_effect",
"reason": "checked",
"requested_at_ms": 1
}
}),
json!({
"kian": {
"type": "control",
"action": "effect-assumption",
"run": run,
"step": "",
"prior_attempt": 1,
"assumed": "no_effect",
"reason": "checked",
"requested_at_ms": 1
}
}),
json!({
"kian": {
"type": "control",
"action": "effect-assumption",
"run": run,
"step": "publish",
"prior_attempt": 0,
"assumed": "no_effect",
"reason": "checked",
"requested_at_ms": 1
}
}),
json!({
"kian": {
"type": "control",
"action": "effect-assumption",
"run": run,
"step": "publish",
"prior_attempt": 1,
"assumed": "effect_landed",
"reason": "checked",
"requested_at_ms": 1
}
}),
json!({
"kian": {
"type": "control",
"action": "effect-assumption",
"run": run,
"step": "publish",
"prior_attempt": 1,
"assumed": "no_effect",
"reason": " ",
"requested_at_ms": 1
}
}),
json!({
"kian": {
"type": "control",
"action": "effect-assumption",
"run": run,
"step": "publish",
"prior_attempt": 1,
"assumed": "no_effect",
"reason": "checked",
"requested_by": null,
"requested_at_ms": 1
}
}),
json!({
"kian": {
"type": "control",
"action": "effect-assumption",
"run": run,
"step": "publish",
"prior_attempt": 1,
"assumed": "no_effect",
"reason": "checked",
"requested_at_ms": 1,
"extra": true
}
}),
] {
assert!(
EffectAssumptionIntent::parse(&malformed).is_err(),
"{malformed}"
);
assert!(EffectAssumptionIntent::is_action(&malformed));
}
let confirm = json!({
"kian": {
"type": "control",
"action": "confirm",
"call_id": "c",
"decision": "approve"
}
});
assert_eq!(EffectAssumptionIntent::parse(&confirm), Ok(None));
}
#[test]
fn effect_assumption_event_parser_rejects_envelope_bytes_and_wrong_actions() {
let envelope = json!({
"kian": {
"type": "control",
"action": "effect-assumption",
"run": Uuid::nil().to_string(),
"step": "publish",
"prior_attempt": 1,
"assumed": "no_effect",
"reason": "checked",
"requested_at_ms": 1
}
});
assert_eq!(
EffectAssumptionIntent::from_event_payload(&envelope),
Ok(None)
);
assert_eq!(
EffectAssumptionIntent::from_event_payload(&json!({
"action": "confirm",
"call_id": "c",
"decision": "approve"
})),
Ok(None)
);
}
#[test]
fn budget_envelope_round_trips_and_is_a_reserved_control_shape() {
let i = BudgetIntent {
tokens: Some(2_000_000),
wall_clock_ms: Some(60_000),
reason: Some("long-horizon task".into()),
requested_by: Some("alice".into()),
requested_at_ms: 1_762_000_000_000,
};
let envelope = i.envelope();
assert_eq!(
envelope,
json!({"kian": {"type": "control", "action": "budget",
"tokens": 2_000_000_u64, "wall_clock_ms": 60_000_u64,
"reason": "long-horizon task", "requested_by": "alice",
"requested_at_ms": 1_762_000_000_000_u64}})
);
assert_eq!(BudgetIntent::parse(&envelope), Some(i.clone()));
assert!(BudgetIntent::is_control_envelope(&envelope));
assert!(ConfirmIntent::is_reserved_shape(&envelope));
let minimal = json!({"kian": {"type": "control", "action": "budget"}});
assert_eq!(
BudgetIntent::parse(&minimal),
Some(BudgetIntent {
tokens: None,
wall_clock_ms: None,
reason: None,
requested_by: None,
requested_at_ms: 0,
})
);
let event = i.event_payload();
assert_eq!(event["action"], json!("budget"));
assert_eq!(event["tokens"], json!(2_000_000_u64));
assert_eq!(event.get("stale"), None);
assert_eq!(
BudgetIntent::parse(&json!({"kian": {"type": "control", "action": "cancel"}})),
None
);
assert!(!BudgetIntent::is_control_envelope(
&json!({"kian": {"type": "control", "action": "interrupt"}})
));
}
#[test]
fn budget_idempotency_key_is_deterministic() {
let sid = SessionId(Uuid::nil());
assert_eq!(
BudgetIntent::idempotency_key(&sid, Some(10), Some(20), 30),
format!("budget:{}:10:20:30", sid.0)
);
assert_eq!(
BudgetIntent::idempotency_key(&sid, None, None, 0),
format!("budget:{}:0:0:0", sid.0)
);
}
}