diff --git a/.crumb b/.crumb index 9559f67..ef3f41c 100644 --- a/.crumb +++ b/.crumb @@ -25,8 +25,8 @@ "generated": { "children": [ { - "digest": "2d3aba84ec7059283089a3519c36336e7d148cbaffe44e02a6423c6c00303126", - "last_commit": "945a63f", + "digest": "8c6acdc9a526bbdc77b97c7f57fbfc452f30e37ae586baeb3f1bca94ef638b41", + "last_commit": "59106f2", "name": "docs", "purpose": "Directory docs. Purpose not yet described by a human." }, @@ -43,27 +43,27 @@ "purpose": "Directory scripts. Purpose not yet described by a human." }, { - "digest": "7cbd75ce692a5afecfdd4b37eb4fbd0bff7fb69fd6672988a859b7ea3bf7a121", - "last_commit": "7288fa6", + "digest": "9b9d657c8664a989a95b74e0e0be8b4c6224939dd63bb58735a7269a43a0df9d", + "last_commit": "59106f2", "name": "src", "purpose": "Directory src. Purpose not yet described by a human." }, { - "digest": "f4bd4396bc580ae13307cfae0811c25db094a9c1b1a5ec06c094f19e20ae6382", - "last_commit": "7288fa6", + "digest": "553b7ce7b77250717e875a812846042ff7b9dba674f0d17213a550feee3065bf", + "last_commit": "59106f2", "name": "tests", "purpose": "Directory tests. Purpose not yet described by a human." } ], - "children_root": "sha256:2eb860620aa5a7d84e02e3673c436798f39bc09ecff9e5bcd908f77be277d692", - "compiled_at": "2026-10-04T18:13:51Z", + "children_root": "sha256:d8ec53ddc9c061bc6dfad5e949fc039883591c9187142fbe6dfc1ac7da9c7b43", + "compiled_at": "2026-10-10T16:04:06Z", "compiler": "crumb-compile/1", - "digest": "sha256:a42b63d14ccc0ee65dedc65f301ab010a62f50f42dabfb6cc68644a496d3ebc4", + "digest": "sha256:38f7c78c5829dc07d3238f0d0b8e126e8f3467cde530781f7d70155f8d58cb0c", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 77, - "generated_at_commit": "7288fa65b22fe45e36a88f44150f21ed8781dc89", - "source_tree": "sha256:3e4f0004ac330c64ebd2a405c3ee1d3cc5d5c0b8e129d3b58d50f7106c572391" + "files": 80, + "generated_at_commit": "59106f26f00645ca8b362c8623c5f48d52664eae", + "source_tree": "sha256:55741903b205bfafd8ff9d3c3f666f6beb0e7a2feca91ab25e8175ad211548ae" }, "owner_lane": "", "seed": { diff --git a/Cargo.lock b/Cargo.lock index 6c3e600..b1b10e0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -25,6 +25,7 @@ dependencies = [ "rusqlite", "serde", "serde_json", + "sha2 0.10.9", "tempfile", "tokio", "tokio-stream", diff --git a/Cargo.toml b/Cargo.toml index e403115..01a8d33 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,7 @@ anyhow = "1.0.104" async-trait = "0.1" parking_lot = "0.12" bytes = "1.6" +sha2 = "0.10" # Canonical AIEN Protocol Crates aien-protocol-types = { path = "../aien-protocols/crates/aien-protocol-types" } diff --git a/docs/.crumb b/docs/.crumb index 18b71d1..eb6ecc1 100644 --- a/docs/.crumb +++ b/docs/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-04T18:13:51Z", + "compiled_at": "2026-10-10T16:04:06Z", "compiler": "crumb-compile/1", - "digest": "sha256:2d3aba84ec7059283089a3519c36336e7d148cbaffe44e02a6423c6c00303126", + "digest": "sha256:8c6acdc9a526bbdc77b97c7f57fbfc452f30e37ae586baeb3f1bca94ef638b41", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 1, - "generated_at_commit": "7288fa65b22fe45e36a88f44150f21ed8781dc89", - "source_tree": "sha256:542eaba79ea3db3c1c44dafc78c0ccfacaecb99eaf630dd2beaf33dd4c78584d" + "files": 2, + "generated_at_commit": "59106f26f00645ca8b362c8623c5f48d52664eae", + "source_tree": "sha256:e7c8114eed38411665a78d8bc2d26ca79f00e6c8eb1e8120655ef1e39f5e45dc" }, "owner_lane": "", "seed": { diff --git a/docs/FAILURE-PROVENANCE.md b/docs/FAILURE-PROVENANCE.md new file mode 100644 index 0000000..bdd7044 --- /dev/null +++ b/docs/FAILURE-PROVENANCE.md @@ -0,0 +1,67 @@ +# Failure provenance and retry classification (issue #38) + +Code: `src/failure.rs` (all public types), wired in `src/agent.rs`, `src/skills.rs` +(`dispatch_classified`) and `src/events/event.rs` (`AegisEvent::StepFailed`). + +AEGIS is out of release v1. Nothing here is wired into a release path. + +## Vocabulary + +`FailureClass`: Rejected, Unavailable, Timeout, Cancelled, Uncertain, Failed, Malformed, ApprovalPending. +`EffectCertainty`: NoEffect, Uncertain, EffectOccurred. +`RetryEligibility`: Retryable { max_attempts } or NotRetryable. Derived by the pure function +`retry_eligibility(class, certainty, idempotent, policy)`. It is never stored and never grants anything. + +Upstream mapping: aien-mcp `Rejected` is `Rejected` + `NoEffect`; `Uncertain` is `Uncertain`; `Finished` has no failure record. + +## Retry rule + +An automatic retry happens only when all hold: class is Unavailable (never Rejected: a policy or gate denial is not retried), certainty is NoEffect, +the skill is on the idempotent list (`skill_effect_profile`), and `RetryPolicy.max_attempts` is above 1 +(default 1, ceiling 5). Every attempt is a new dispatch through the gated path (probe gate, allowlist, +handler). Timeout, Cancelled, Uncertain, Failed, Malformed and ApprovalPending are never retried. +ApprovalPending also stops the run: the later calls of that turn are not run and the model is not asked again. + +## State and error mapping + +| Existing site | Signal today | FailureClass | EffectCertainty | +|---|---|---|---| +| `enforcement::probe_gate` refusal (`skills.rs` gated path) | Err string | Rejected | NoEffect | +| `enforcement::pre_dispatch_check`: not on allowlist, empty name, non-object args, bad shell command | Err string | Rejected | NoEffect | +| Skill name not in registry | "not found in registry" | Rejected | NoEffect | +| Handler error starting with "Unavailable" (cortex, telemetry stubs) | Err string | Unavailable | NoEffect | +| Handler error, idempotent skill (read_file, list_dir, git_status) | Err string | Failed | NoEffect | +| Handler error, mutating skill (write_file, bash_eval) | Err string | Failed | EffectOccurred (conservative) | +| Per-call deadline (`FailurePolicy.tool_timeout`), idempotent skill | new | Timeout | NoEffect | +| Per-call deadline, mutating skill | new | Timeout | Uncertain | +| `CancelToken` set before dispatch | new | Cancelled | NoEffect | +| `CancelToken` set while running, idempotent / mutating | new | Cancelled | NoEffect / Uncertain | +| Custom `ToolDispatcher` reports lost response | `ToolFault` | Uncertain | Uncertain | +| Custom `ToolDispatcher` reports unparsable result | `ToolFault` | Malformed | as reported | +| Custom `ToolDispatcher` reports human approval needed | `ToolFault` | ApprovalPending | as reported | +| `ExecutionAuthority::authorize` Err (broker seam, not used by `execute_task` today) | Err string | Unavailable | NoEffect | +| `DoctrineDecision` deny at the broker | decision | Rejected | NoEffect | +| `ActionStatus::Denied` / `Failed` | status | Rejected / Failed | NoEffect / as recorded | +| `RunState::Failed` / `Cancelled` / `WaitingForApproval` | state | derived from last record / Cancelled / ApprovalPending | from last record | +| Inference endpoint unreachable (`execute_task` returns Err) | Err | not classified (out of scope, engine error semantics unchanged) | n/a | +| Model tool arguments that are not valid JSON | wrapped as `{"raw": ...}` | unchanged | n/a | + +Rows marked broker, ActionStatus and RunState document how those states would map; this change does not alter +those code paths. Only the agent tool-call rows are exercised by tests. + +## Record shape + +`FailureRecord`: sequence (stable order, starts at 1 per run), run_id, step_index, tool_call_id, +parent_call_id (the directly preceding failed call, a causal hint), tool_name, attempt, class, +effect_certainty, created_at (call scheduled, ms), failed_at (ms), cause (max 8 entries, each message at most +512 bytes, payload stored only as a sha256 digest, argument strings echoed in messages replaced by `[redacted]`), +cause_truncated. + +Tool error text sent back to the model and stored in `ToolExecutionRecord.output` passes through the same +redaction as the failure record. `ToolExecutionRecord.arguments` is unchanged and still holds the raw arguments +(pre-existing behaviour, not part of this change). + +`ToolExecutionRecord.failure` holds the terminal record; `retry_failures` holds earlier failed attempts. +Both default to empty so older persisted JSON still loads. Every failed attempt is also published as +`AegisEvent::StepFailed` on the `EventBus` when one is attached (`AgentEngine::with_event_bus`). +`root_cause(records, start)` follows parent links to the original failure. diff --git a/src/.crumb b/src/.crumb index a56801e..5441a10 100644 --- a/src/.crumb +++ b/src/.crumb @@ -39,8 +39,8 @@ "purpose": "Directory src/defense. Purpose not yet described by a human." }, { - "digest": "e30659e60d0a3efae1eb9bc4a0054bacb2656ff8456c000e4e9870b06378ddfd", - "last_commit": "d8d4585", + "digest": "512fab250fa949734a143c79571f82ac993c503fcd2ac71f699cf34415582481", + "last_commit": "d98ba21", "name": "events", "purpose": "Directory src/events. Purpose not yet described by a human." }, @@ -69,15 +69,15 @@ "purpose": "Directory src/sessions. Purpose not yet described by a human." } ], - "children_root": "sha256:61bc66a5bbca16ac47c232a6bd6ff93b90a95601a6a2c7f77b705d446d29899e", - "compiled_at": "2026-10-04T18:13:51Z", + "children_root": "sha256:eafd79d762cf1c61e44c50176c2dfe4636950452ab07f0e54908276de92a5aa2", + "compiled_at": "2026-10-10T16:04:06Z", "compiler": "crumb-compile/1", - "digest": "sha256:7cbd75ce692a5afecfdd4b37eb4fbd0bff7fb69fd6672988a859b7ea3bf7a121", + "digest": "sha256:9b9d657c8664a989a95b74e0e0be8b4c6224939dd63bb58735a7269a43a0df9d", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 47, - "generated_at_commit": "7288fa65b22fe45e36a88f44150f21ed8781dc89", - "source_tree": "sha256:14c10750aceaae8190f5e23582515fd168cf6e543aa376920cef16c95a1ed8de" + "files": 48, + "generated_at_commit": "59106f26f00645ca8b362c8623c5f48d52664eae", + "source_tree": "sha256:ba81f730236b2440dd667c9d0ae62df98dac3a39df29fe9ca5a21db97d327e95" }, "owner_lane": "", "seed": { diff --git a/src/agent.rs b/src/agent.rs index 48b119b..c86c0b0 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -1,12 +1,18 @@ use serde::{Deserialize, Serialize}; use serde_json::json; use std::sync::Arc; -use std::time::Instant; +use std::time::{Duration, Instant}; use tracing::info; +use crate::events::{AegisEvent, EventBus, EventEnvelope}; +use crate::failure::{ + redact_payload_echoes, retry_loop, skill_effect_profile, CancelToken, EffectCertainty, + FailureClass, FailureRecord, RetryPolicy, ToolDispatcher, ToolFault, +}; use crate::inference::InferenceEngine; use crate::persistence::Database; -use crate::skills::{SkillExecutionRequest, SkillRegistry}; +use crate::sessions::id::RunId; +use crate::skills::SkillRegistry; pub const DEFAULT_MAX_CONTEXT_TOKENS: usize = 8192; @@ -17,6 +23,20 @@ pub struct ToolExecutionRecord { pub arguments: serde_json::Value, pub output: String, pub success: bool, + /// Terminal failure provenance. Absent on success and in older records. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub failure: Option, + /// Earlier failed attempts of this same call, oldest first. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub retry_failures: Vec, +} + +/// Failure handling knobs. Defaults keep the old behaviour: one attempt, +/// no deadline. +#[derive(Debug, Clone, Copy, Default)] +pub struct FailurePolicy { + pub retry: RetryPolicy, + pub tool_timeout: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -40,6 +60,11 @@ pub struct AgentEngine { inference: Arc, skills: Arc, db: Option>, + dispatcher: Arc, + policy: FailurePolicy, + cancel: CancelToken, + events: Option<(EventBus, Option)>, + run_id: Option, } impl AgentEngine { @@ -50,8 +75,84 @@ impl AgentEngine { ) -> Self { Self { inference, + dispatcher: skills.clone(), skills, db, + policy: FailurePolicy::default(), + cancel: CancelToken::new(), + events: None, + run_id: None, + } + } + + /// Replaces the tool dispatch seam (default: the skill registry's gated path). + pub fn with_dispatcher(mut self, dispatcher: Arc) -> Self { + self.dispatcher = dispatcher; + self + } + + pub fn with_failure_policy(mut self, policy: FailurePolicy) -> Self { + self.policy = policy; + self + } + + pub fn with_cancel_token(mut self, cancel: CancelToken) -> Self { + self.cancel = cancel; + self + } + + /// Publishes `AegisEvent::StepFailed` on this bus for every failed attempt. + pub fn with_event_bus(mut self, bus: EventBus, session_id: Option) -> Self { + self.events = Some((bus, session_id)); + self + } + + /// Fixes the run id stamped on failure records (default: a fresh id per task). + pub fn with_run_id(mut self, run_id: impl Into) -> Self { + self.run_id = Some(run_id.into()); + self + } + + /// One fresh gated dispatch with cancellation and deadline applied. + /// A cancel or timeout of a non-idempotent call leaves the effect Uncertain. + async fn attempt_tool( + &self, + name: &str, + args: &serde_json::Value, + idempotent: bool, + ) -> Result { + let unknown = if idempotent { + EffectCertainty::NoEffect + } else { + EffectCertainty::Uncertain + }; + if self.cancel.is_cancelled() { + return Err(ToolFault::new( + FailureClass::Cancelled, + EffectCertainty::NoEffect, + "cancelled before dispatch", + )); + } + let guarded = async { + tokio::select! { + r = self.dispatcher.dispatch(name, args) => r, + _ = self.cancel.cancelled() => Err(ToolFault::new( + FailureClass::Cancelled, + unknown, + "cancelled while running", + )), + } + }; + match self.policy.tool_timeout { + Some(d) => match tokio::time::timeout(d, guarded).await { + Ok(r) => r, + Err(_) => Err(ToolFault::new( + FailureClass::Timeout, + unknown, + format!("deadline of {} ms exceeded", d.as_millis()), + )), + }, + None => guarded.await, } } @@ -126,6 +227,13 @@ impl AgentEngine { let mut final_response = String::new(); let mut turns_taken = 0; let mut completed = false; + let run_id = self + .run_id + .clone() + .unwrap_or_else(|| RunId::new().as_str().to_string()); + let mut failure_seq: u64 = 0; + let mut last_failed_call: Option = None; + let mut halted: Option = None; for turn in 1..=max_turns { turns_taken = turn; @@ -175,26 +283,79 @@ impl AgentEngine { let args: serde_json::Value = serde_json::from_str(&tc.function.arguments) .unwrap_or_else(|_| json!({"raw": tc.function.arguments})); - let req = SkillExecutionRequest { - skill_name: tc.function.name.clone(), - arguments: args.clone(), - }; + // Every attempt is a new gated dispatch (allowlist and probe + // gate run again). Retry happens only for idempotent calls + // that were refused or unreachable with no effect. + let idempotent = skill_effect_profile(&tc.function.name).idempotent; + let (result, failed_attempts) = + retry_loop(&self.policy.retry, idempotent, |_| { + self.attempt_tool(&tc.function.name, &args, idempotent) + }) + .await; + + let mut failure_records: Vec = Vec::new(); + for a in &failed_attempts { + failure_seq += 1; + let mut rec = FailureRecord::new( + failure_seq, + run_id.clone(), + turn, + tc.id.clone(), + last_failed_call.clone(), + tc.function.name.clone(), + a.attempt, + a.fault.class, + a.fault.certainty, + a.created_at, + a.failed_at, + ); + let msg = redact_payload_echoes(&a.fault.message, &args); + rec.push_cause("tool_dispatch", &msg, Some(&args)); + if let Some((bus, session_id)) = &self.events { + let _ = bus.publish(EventEnvelope::new( + AegisEvent::StepFailed { + failure: rec.clone(), + }, + session_id.clone(), + Some(run_id.clone()), + failure_seq, + )); + } + failure_records.push(rec); + } - let res = self.skills.execute_gated(&req).await; - let output_str = if res.success { - res.output.clone() - } else { - res.error - .clone() - .unwrap_or_else(|| "Unknown error".to_string()) + let (output_str, success) = match &result { + Ok(out) => (out.clone(), true), + Err(fault) => (redact_payload_echoes(&fault.message, &args), false), }; + let failure = if success { None } else { failure_records.pop() }; + + if let Err(fault) = &result { + last_failed_call = Some(tc.id.clone()); + match fault.class { + FailureClass::ApprovalPending => { + halted = Some(format!( + "Halted: tool call {} is waiting for approval and will not be replayed automatically.", + tc.id + )); + } + FailureClass::Cancelled => { + halted = Some(format!("Run cancelled during tool call {}.", tc.id)); + } + _ => {} + } + } else { + last_failed_call = None; + } tool_exec_records.push(ToolExecutionRecord { call_id: tc.id.clone(), tool_name: tc.function.name.clone(), arguments: args, output: output_str.clone(), - success: res.success, + success, + failure, + retry_failures: failure_records, }); messages.push(json!({ @@ -202,6 +363,10 @@ impl AgentEngine { "tool_call_id": tc.id, "content": output_str })); + + if halted.is_some() { + break; + } } steps.push(AgentStep { @@ -209,6 +374,10 @@ impl AgentEngine { thought, tool_calls: tool_exec_records, }); + if let Some(reason) = halted.take() { + final_response = reason; + break; + } } else { let content = turn_res.content.unwrap_or_default(); final_response = if !content.trim().is_empty() { @@ -256,6 +425,7 @@ impl AgentEngine { #[cfg(test)] mod tests { use super::*; + use crate::skills::SkillExecutionRequest; use crate::HttpInferenceBackend; #[tokio::test] diff --git a/src/events/.crumb b/src/events/.crumb index 687aa4d..5cd819e 100644 --- a/src/events/.crumb +++ b/src/events/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-04T18:13:51Z", + "compiled_at": "2026-10-10T15:56:06Z", "compiler": "crumb-compile/1", - "digest": "sha256:e30659e60d0a3efae1eb9bc4a0054bacb2656ff8456c000e4e9870b06378ddfd", + "digest": "sha256:512fab250fa949734a143c79571f82ac993c503fcd2ac71f699cf34415582481", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 5, - "generated_at_commit": "7288fa65b22fe45e36a88f44150f21ed8781dc89", - "source_tree": "sha256:524f9a53c8a46430330937f899070bef32d392944ca6e3d38c3f27886bbc2fa6" + "generated_at_commit": "b805c8890675e0e9ddc3eec065ad09061a58dc3a", + "source_tree": "sha256:5e6da4bc45d00e5c2d1a061ee8d50e563fda9056deb87772438b90888a0cff7b" }, "owner_lane": "", "seed": { diff --git a/src/events/event.rs b/src/events/event.rs index 3ccb0b9..301ae2d 100644 --- a/src/events/event.rs +++ b/src/events/event.rs @@ -30,6 +30,12 @@ pub enum AegisEvent { error: String, }, + /// A tool call failed. Carries the structured provenance record; never + /// carries raw tool arguments. Does not map to a canonical agent event. + StepFailed { + failure: crate::failure::FailureRecord, + }, + AssistantDelta { text: String, }, diff --git a/src/failure.rs b/src/failure.rs new file mode 100644 index 0000000..e16b53c --- /dev/null +++ b/src/failure.rs @@ -0,0 +1,562 @@ +//! Structured failure provenance and effect-safe retry classification. +//! +//! This module is the single public surface for failure vocabulary in AEGIS. +//! It adds no scheduler and no authority. It only describes what happened to +//! a tool call, and derives (never grants) whether an automatic retry is +//! allowed. Every attempt, including a retry, is a fresh dispatch through the +//! normal gated path, so the gate stays authoritative on each new request. +//! +//! Vocabulary follows aien-mcp `CallOutcome {Finished, Rejected, Uncertain}`: +//! `Rejected` means no effect, `Uncertain` means the effect may have happened. + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::future::Future; + +/// Maximum number of entries kept in a cause chain. +pub const MAX_CAUSE_ENTRIES: usize = 8; +/// Maximum size in bytes of one cause message. +pub const MAX_CAUSE_MESSAGE_BYTES: usize = 512; +/// Hard ceiling on attempts per tool call, whatever the policy says. +pub const MAX_ATTEMPTS_CEILING: u32 = 5; +/// Text that replaces a secret-looking argument value found in a message. +pub const REDACTION_PLACEHOLDER: &str = "[redacted]"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FailureClass { + /// Refused before acting (allowlist, probe gate, invalid arguments, not found). + Rejected, + /// Backend, authority or runtime not reachable before any effect. + Unavailable, + /// Deadline hit; certainty comes from the skill contract. + Timeout, + /// Cancelled by operator or parent; certainty comes from the skill contract. + Cancelled, + /// The effect may have happened (lost response). + Uncertain, + /// The handler ran and reported an error. + Failed, + /// The tool result was unparsable or broke its schema. + Malformed, + /// Not a failure: waiting for a human. Terminal for this attempt. + ApprovalPending, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EffectCertainty { + NoEffect, + Uncertain, + EffectOccurred, +} + +/// Derived, never stored as a grant. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RetryEligibility { + Retryable { max_attempts: u32 }, + NotRetryable, +} + +/// Retry policy. The default is one attempt, which means no retry. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RetryPolicy { + pub max_attempts: u32, +} + +impl Default for RetryPolicy { + fn default() -> Self { + Self { max_attempts: 1 } + } +} + +/// Pure retry rule. A retry is possible only when the backend was unreachable +/// before acting (`Unavailable`), no effect occurred, the capability is marked +/// idempotent, and the policy allows more than one attempt. A `Rejected` +/// outcome (policy or gate denial) is never retried. +pub fn retry_eligibility( + class: FailureClass, + certainty: EffectCertainty, + idempotent: bool, + policy: &RetryPolicy, +) -> RetryEligibility { + let class_ok = class == FailureClass::Unavailable; + let attempts = policy.max_attempts.min(MAX_ATTEMPTS_CEILING); + if class_ok && certainty == EffectCertainty::NoEffect && idempotent && attempts > 1 { + RetryEligibility::Retryable { + max_attempts: attempts, + } + } else { + RetryEligibility::NotRetryable + } +} + +/// What the skill contract says about a capability. Unknown names are treated +/// as mutating (not idempotent). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SkillEffectProfile { + pub idempotent: bool, +} + +pub fn skill_effect_profile(skill_name: &str) -> SkillEffectProfile { + let idempotent = matches!( + skill_name, + "read_file" | "list_dir" | "git_status" | "cortex.search" | "cortex_recall" + ); + SkillEffectProfile { idempotent } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct CauseEntry { + pub source: String, + /// Truncated to `MAX_CAUSE_MESSAGE_BYTES`. + pub message: String, + /// sha256 of the canonical payload; the payload itself is never stored. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub payload_digest: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FailureRecord { + /// Stable order among failures of one run (starts at 1). + pub sequence: u64, + pub run_id: String, + pub step_index: usize, + pub tool_call_id: String, + #[serde(default)] + pub parent_call_id: Option, + pub tool_name: String, + /// 1 based attempt number for this tool call. + pub attempt: u32, + pub class: FailureClass, + pub effect_certainty: EffectCertainty, + /// Scheduling point, milliseconds since the Unix epoch. + pub created_at: i64, + /// Terminal failure point, milliseconds since the Unix epoch. + pub failed_at: i64, + pub cause: Vec, + #[serde(default)] + pub cause_truncated: bool, +} + +/// Keeps at most `max` bytes, cutting on a character boundary. +pub fn truncate_bytes(s: &str, max: usize) -> String { + if s.len() <= max { + return s.to_string(); + } + let mut end = max; + while end > 0 && !s.is_char_boundary(end) { + end -= 1; + } + s[..end].to_string() +} + +/// sha256 of the compact JSON form, as `sha256:`. +pub fn payload_digest(payload: &serde_json::Value) -> String { + let bytes = serde_json::to_vec(payload).unwrap_or_default(); + let digest = Sha256::digest(&bytes); + let mut out = String::from("sha256:"); + for b in digest { + out.push_str(&format!("{:02x}", b)); + } + out +} + +fn collect_strings(v: &serde_json::Value, out: &mut Vec) { + match v { + serde_json::Value::String(s) => { + if s.len() >= 4 { + out.push(s.clone()); + } + } + serde_json::Value::Array(a) => a.iter().for_each(|x| collect_strings(x, out)), + serde_json::Value::Object(m) => m.values().for_each(|x| collect_strings(x, out)), + _ => {} + } +} + +/// Replaces every argument string value (4 bytes or longer) that appears in +/// `message`, so an error text that echoes a caller payload cannot leak it. +pub fn redact_payload_echoes(message: &str, args: &serde_json::Value) -> String { + let mut values = Vec::new(); + collect_strings(args, &mut values); + // Longest first so a long value is not half replaced by a shorter one. + values.sort_by_key(|v| std::cmp::Reverse(v.len())); + let mut out = message.to_string(); + for v in values { + if out.contains(&v) { + out = out.replace(&v, REDACTION_PLACEHOLDER); + } + } + out +} + +pub fn now_millis() -> i64 { + chrono::Utc::now().timestamp_millis() +} + +impl FailureRecord { + #[allow(clippy::too_many_arguments)] + pub fn new( + sequence: u64, + run_id: impl Into, + step_index: usize, + tool_call_id: impl Into, + parent_call_id: Option, + tool_name: impl Into, + attempt: u32, + class: FailureClass, + effect_certainty: EffectCertainty, + created_at: i64, + failed_at: i64, + ) -> Self { + Self { + sequence, + run_id: run_id.into(), + step_index, + tool_call_id: tool_call_id.into(), + parent_call_id, + tool_name: tool_name.into(), + attempt, + class, + effect_certainty, + created_at, + failed_at, + cause: Vec::new(), + cause_truncated: false, + } + } + + /// Appends one cause. The message is cut to 512 bytes. Past 8 entries the + /// extra causes are dropped and `cause_truncated` is set. + pub fn push_cause( + &mut self, + source: impl Into, + message: &str, + payload: Option<&serde_json::Value>, + ) { + if self.cause.len() >= MAX_CAUSE_ENTRIES { + self.cause_truncated = true; + return; + } + self.cause.push(CauseEntry { + source: source.into(), + message: truncate_bytes(message, MAX_CAUSE_MESSAGE_BYTES), + payload_digest: payload.map(payload_digest), + }); + } + + pub fn with_cause( + mut self, + source: impl Into, + message: &str, + payload: Option<&serde_json::Value>, + ) -> Self { + self.push_cause(source, message, payload); + self + } +} + +/// Follows `parent_call_id` links to the original failure. Bounded by the +/// number of records, so a cycle cannot loop forever. Returns the record +/// itself when it has no known parent among `records`. +pub fn root_cause<'a>( + records: &'a [FailureRecord], + start: &FailureRecord, +) -> Option<&'a FailureRecord> { + let mut current = records + .iter() + .find(|r| r.tool_call_id == start.tool_call_id && r.attempt == start.attempt)?; + for _ in 0..=records.len() { + let parent = current + .parent_call_id + .as_ref() + .and_then(|pid| records.iter().rfind(|r| &r.tool_call_id == pid)); + match parent { + Some(p) if p.sequence != current.sequence => current = p, + _ => return Some(current), + } + } + Some(current) +} + +/// A classified tool-level fault, before it is stamped with run identifiers. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ToolFault { + pub class: FailureClass, + pub certainty: EffectCertainty, + pub message: String, +} + +impl ToolFault { + pub fn new( + class: FailureClass, + certainty: EffectCertainty, + message: impl Into, + ) -> Self { + Self { + class, + certainty, + message: message.into(), + } + } + + pub fn rejected(message: impl Into) -> Self { + Self::new(FailureClass::Rejected, EffectCertainty::NoEffect, message) + } + + pub fn unavailable(message: impl Into) -> Self { + Self::new( + FailureClass::Unavailable, + EffectCertainty::NoEffect, + message, + ) + } +} + +/// One failed attempt with its own timing. +#[derive(Debug, Clone)] +pub struct AttemptFailure { + pub attempt: u32, + pub fault: ToolFault, + pub created_at: i64, + pub failed_at: i64, +} + +/// Bounded retry helper. `attempt_fn` is called once per attempt with the +/// 1 based attempt number and must perform a brand new gated dispatch each +/// time; nothing from an earlier attempt is reused. Retries happen only when +/// `retry_eligibility` says so. Returns the final result and every failed +/// attempt in order. +pub async fn retry_loop( + policy: &RetryPolicy, + idempotent: bool, + mut attempt_fn: F, +) -> (Result, Vec) +where + F: FnMut(u32) -> Fut, + Fut: Future>, +{ + let mut failures = Vec::new(); + let mut attempt = 1u32; + loop { + let created_at = now_millis(); + match attempt_fn(attempt).await { + Ok(v) => return (Ok(v), failures), + Err(fault) => { + failures.push(AttemptFailure { + attempt, + fault: fault.clone(), + created_at, + failed_at: now_millis(), + }); + let again = + match retry_eligibility(fault.class, fault.certainty, idempotent, policy) { + RetryEligibility::Retryable { max_attempts } => attempt < max_attempts, + RetryEligibility::NotRetryable => false, + }; + if !again { + return (Err(fault), failures); + } + attempt += 1; + } + } + } +} + +/// Seam between the agent loop and the gated tool path. The default +/// implementation is `SkillRegistry`, whose dispatch runs the allowlist and +/// the probe gate on every call. Tests and other runtimes may supply their own. +#[async_trait::async_trait] +pub trait ToolDispatcher: Send + Sync { + async fn dispatch( + &self, + skill_name: &str, + arguments: &serde_json::Value, + ) -> Result; +} + +/// Cooperative cancellation flag that can also wake an in-flight await. +#[derive(Clone, Default)] +pub struct CancelToken { + flag: std::sync::Arc, + notify: std::sync::Arc, +} + +impl CancelToken { + pub fn new() -> Self { + Self::default() + } + + pub fn cancel(&self) { + self.flag.store(true, std::sync::atomic::Ordering::SeqCst); + self.notify.notify_waiters(); + } + + pub fn is_cancelled(&self) -> bool { + self.flag.load(std::sync::atomic::Ordering::SeqCst) + } + + pub async fn cancelled(&self) { + loop { + let waiter = self.notify.notified(); + if self.is_cancelled() { + return; + } + waiter.await; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn rec(seq: u64, call: &str, parent: Option<&str>) -> FailureRecord { + FailureRecord::new( + seq, + "run_1", + 1, + call, + parent.map(|p| p.to_string()), + "read_file", + 1, + FailureClass::Failed, + EffectCertainty::NoEffect, + 1, + 2, + ) + } + + #[test] + fn eligibility_only_for_no_effect_idempotent_rejected_or_unavailable() { + let policy = RetryPolicy { max_attempts: 3 }; + let classes = [ + FailureClass::Rejected, + FailureClass::Unavailable, + FailureClass::Timeout, + FailureClass::Cancelled, + FailureClass::Uncertain, + FailureClass::Failed, + FailureClass::Malformed, + FailureClass::ApprovalPending, + ]; + let certainties = [ + EffectCertainty::NoEffect, + EffectCertainty::Uncertain, + EffectCertainty::EffectOccurred, + ]; + for c in classes { + for e in certainties { + for idem in [true, false] { + let got = retry_eligibility(c, e, idem, &policy); + let expect_retry = + c == FailureClass::Unavailable && e == EffectCertainty::NoEffect && idem; + assert_eq!( + got == RetryEligibility::Retryable { max_attempts: 3 }, + expect_retry, + "{:?} {:?} idempotent={}", + c, + e, + idem + ); + } + } + } + } + + #[test] + fn default_policy_never_retries_and_ceiling_applies() { + let d = RetryPolicy::default(); + assert_eq!( + retry_eligibility( + FailureClass::Unavailable, + EffectCertainty::NoEffect, + true, + &d + ), + RetryEligibility::NotRetryable + ); + let big = RetryPolicy { max_attempts: 1000 }; + assert_eq!( + retry_eligibility( + FailureClass::Unavailable, + EffectCertainty::NoEffect, + true, + &big + ), + RetryEligibility::Retryable { + max_attempts: MAX_ATTEMPTS_CEILING + } + ); + } + + #[test] + fn cause_chain_is_bounded_and_messages_truncated() { + let mut r = rec(1, "c1", None); + for i in 0..20 { + r.push_cause("test", &format!("{}{}", i, "x".repeat(2000)), None); + } + assert_eq!(r.cause.len(), MAX_CAUSE_ENTRIES); + assert!(r.cause_truncated); + assert!(r + .cause + .iter() + .all(|c| c.message.len() <= MAX_CAUSE_MESSAGE_BYTES)); + // Multi byte text is cut on a character boundary. + let s = "é".repeat(600); + let t = truncate_bytes(&s, MAX_CAUSE_MESSAGE_BYTES); + assert!(t.len() <= MAX_CAUSE_MESSAGE_BYTES); + assert!(t.chars().all(|c| c == 'é')); + } + + #[test] + fn payload_is_digest_only_and_secret_never_serialized() { + let secret = "sk-live-SEEDED-SECRET-9f3a"; + let args = json!({"path": "/x", "token": secret, "nested": [{"k": secret}]}); + let echoed = format!("cannot open {} for reading", secret); + let msg = redact_payload_echoes(&echoed, &args); + let rec = rec(1, "c1", None).with_cause("tool", &msg, Some(&args)); + let ser = serde_json::to_string(&rec).unwrap(); + let dbg = format!("{:?}", rec); + assert!(!ser.contains(secret), "serialized leaked: {}", ser); + assert!(!dbg.contains(secret), "debug leaked: {}", dbg); + assert!(ser.contains("sha256:")); + assert!(ser.contains(REDACTION_PLACEHOLDER)); + } + + #[test] + fn root_cause_follows_parents_and_survives_cycles() { + let records = vec![ + rec(1, "a", None), + rec(2, "b", Some("a")), + rec(3, "c", Some("b")), + ]; + assert_eq!(root_cause(&records, &records[2]).unwrap().tool_call_id, "a"); + let cyc = vec![rec(1, "a", Some("b")), rec(2, "b", Some("a"))]; + assert!(root_cause(&cyc, &cyc[0]).is_some()); + } + + #[test] + fn old_json_without_new_fields_still_loads() { + let old = + r#"{"call_id":"c","tool_name":"read_file","arguments":{},"output":"o","success":true}"#; + let r: crate::agent::ToolExecutionRecord = serde_json::from_str(old).unwrap(); + assert!(r.failure.is_none()); + assert!(r.retry_failures.is_empty()); + } + + #[tokio::test] + async fn cancel_token_wakes_waiter() { + let t = CancelToken::new(); + let t2 = t.clone(); + let h = tokio::spawn(async move { t2.cancelled().await }); + tokio::task::yield_now().await; + t.cancel(); + h.await.unwrap(); + // Already cancelled: returns immediately. + t.cancelled().await; + } +} diff --git a/src/lib.rs b/src/lib.rs index c488946..3b723e2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,6 +3,7 @@ pub mod auth; pub mod defense; pub mod events; pub mod execution; +pub mod failure; pub mod gateway; pub mod heartbeat; pub mod inference; @@ -14,11 +15,16 @@ pub mod sessions; pub mod skills; pub mod vault; -pub use agent::{AgentEngine, AgentExecutionResult, AgentStep}; +pub use agent::{AgentEngine, AgentExecutionResult, AgentStep, FailurePolicy, ToolExecutionRecord}; pub use auth::{resolve_bind_addr, OperatorAuth}; pub use defense::{Approval, ApprovalStatus, ContainmentLevel, DefenseReceipt, DoctrineDecision}; pub use events::{AegisEvent, EventBus, EventEnvelope, EventId, EventSubscriber}; pub use execution::{Action, ActionReceipt, ActionRequest, ActionStatus, ExecutionAuthority}; +pub use failure::{ + retry_eligibility, root_cause, skill_effect_profile, AttemptFailure, CancelToken, CauseEntry, + EffectCertainty, FailureClass, FailureRecord, RetryEligibility, RetryPolicy, ToolDispatcher, + ToolFault, +}; pub use gateway::{create_router, start_gateway, GatewayState, HealthResponse}; pub use heartbeat::{HeartbeatEngine, PulseReceipt}; pub use inference::{ diff --git a/src/skills.rs b/src/skills.rs index ea990ac..65cd144 100644 --- a/src/skills.rs +++ b/src/skills.rs @@ -1,3 +1,6 @@ +use crate::failure::{ + skill_effect_profile, EffectCertainty, FailureClass, ToolDispatcher, ToolFault, +}; use crate::security::WorkspaceCapability; use serde::{Deserialize, Serialize}; use std::collections::HashMap; @@ -121,6 +124,40 @@ impl SkillRegistry { self.execute(req) } + /// Same gates as `execute_gated` (probe gate, then membrane, then handler) + /// but returns a typed fault instead of a bare error string. Each call is a + /// fresh dispatch; nothing is cached between calls. + pub async fn dispatch_classified( + &self, + skill_name: &str, + arguments: &serde_json::Value, + ) -> Result { + crate::enforcement::probe_gate(skill_name, arguments) + .await + .map_err(ToolFault::rejected)?; + crate::enforcement::pre_dispatch_check(skill_name, arguments) + .map_err(ToolFault::rejected)?; + let handler = { + let map = self.skills.read().unwrap(); + map.get(skill_name).map(|(_, h)| h.clone()) + }; + let Some(h) = handler else { + return Err(ToolFault::rejected(format!( + "Skill '{}' not found in registry", + skill_name + ))); + }; + h(arguments.clone()).map_err(|err| { + if err.starts_with("Unavailable") { + ToolFault::unavailable(err) + } else if skill_effect_profile(skill_name).idempotent { + ToolFault::new(FailureClass::Failed, EffectCertainty::NoEffect, err) + } else { + ToolFault::new(FailureClass::Failed, EffectCertainty::EffectOccurred, err) + } + }) + } + pub fn execute(&self, req: &SkillExecutionRequest) -> SkillExecutionResponse { if let Err(reason) = crate::enforcement::pre_dispatch_check(&req.skill_name, &req.arguments) { @@ -360,6 +397,17 @@ impl SkillRegistry { } } +#[async_trait::async_trait] +impl ToolDispatcher for SkillRegistry { + async fn dispatch( + &self, + skill_name: &str, + arguments: &serde_json::Value, + ) -> Result { + self.dispatch_classified(skill_name, arguments).await + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/tests/.crumb b/tests/.crumb index c854c58..b828c75 100644 --- a/tests/.crumb +++ b/tests/.crumb @@ -20,14 +20,14 @@ } ], "children_root": "sha256:2f0b999b8999ad3095c8081fb342d506f27f7b07b31452b67140d330ccf4dc76", - "compiled_at": "2026-10-04T18:13:51Z", + "compiled_at": "2026-10-10T16:04:06Z", "compiler": "crumb-compile/1", - "digest": "sha256:f4bd4396bc580ae13307cfae0811c25db094a9c1b1a5ec06c094f19e20ae6382", + "digest": "sha256:553b7ce7b77250717e875a812846042ff7b9dba674f0d17213a550feee3065bf", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 9, - "generated_at_commit": "7288fa65b22fe45e36a88f44150f21ed8781dc89", - "source_tree": "sha256:eef5040b25d3c7f1141d6420234488b1411af9a947fcfb695c7478f64a91ead3" + "files": 10, + "generated_at_commit": "59106f26f00645ca8b362c8623c5f48d52664eae", + "source_tree": "sha256:5c2fdd65496a766d892518fb6ae28568d7e5a62345e63fa907b6892efaefedf7" }, "owner_lane": "", "seed": { diff --git a/tests/failure_provenance_tests.rs b/tests/failure_provenance_tests.rs new file mode 100644 index 0000000..f49b9d8 --- /dev/null +++ b/tests/failure_provenance_tests.rs @@ -0,0 +1,650 @@ +//! Failure provenance and effect-safe retry tests (issue #38). +//! Deterministic: scripted model turns, scripted tool dispatcher, no network. + +use aegis::agent::FailurePolicy; +use aegis::{ + root_cause, AegisEvent, AgentEngine, CancelToken, ChatStream, ChatTurnResponse, + EffectCertainty, EventBus, FailureClass, FailureRecord, InferenceEngine, RetryPolicy, + SkillRegistry, ToolCallFunction, ToolCallItem, ToolDispatcher, ToolFault, +}; +use async_trait::async_trait; +use std::collections::{HashMap, VecDeque}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +const SECRET: &str = "sk-live-SEEDED-SECRET-9f3a77"; + +struct ScriptedModel { + turns: Mutex>, + asked: AtomicUsize, + seen: Mutex>, +} + +impl ScriptedModel { + fn new(turns: Vec) -> Arc { + Arc::new(Self { + turns: Mutex::new(turns.into()), + asked: AtomicUsize::new(0), + seen: Mutex::new(Vec::new()), + }) + } +} + +fn calls(items: &[(&str, &str, serde_json::Value)]) -> ChatTurnResponse { + ChatTurnResponse { + content: None, + reasoning: None, + tool_calls: Some( + items + .iter() + .map(|(id, name, args)| ToolCallItem { + id: id.to_string(), + call_type: "function".to_string(), + function: ToolCallFunction { + name: name.to_string(), + arguments: args.to_string(), + }, + }) + .collect(), + ), + finish_reason: Some("tool_calls".to_string()), + } +} + +fn done() -> ChatTurnResponse { + ChatTurnResponse { + content: Some("finished".to_string()), + reasoning: None, + tool_calls: None, + finish_reason: Some("stop".to_string()), + } +} + +#[async_trait] +impl InferenceEngine for ScriptedModel { + fn model_id(&self) -> String { + "scripted".into() + } + fn endpoint(&self) -> String { + "none".into() + } + async fn generate_with_tokens( + &self, + _p: &str, + _s: Option<&str>, + _t: Option, + _m: Option, + ) -> Result> { + Ok(String::new()) + } + async fn generate_chat( + &self, + _m: &[serde_json::Value], + _t: Option, + _x: Option, + ) -> Result> { + Ok(String::new()) + } + async fn generate_chat_with_tools( + &self, + m: &[serde_json::Value], + _tools: Option<&[serde_json::Value]>, + _t: Option, + _x: Option, + ) -> Result> { + self.asked.fetch_add(1, Ordering::SeqCst); + self.seen + .lock() + .unwrap() + .push(serde_json::to_string(m).unwrap()); + Ok(self.turns.lock().unwrap().pop_front().unwrap_or_else(done)) + } + async fn stream_chat( + &self, + _m: &[serde_json::Value], + _t: Option, + _x: Option, + ) -> Result> { + Err("not used".into()) + } + async fn check_health(&self) -> bool { + true + } +} + +#[derive(Clone)] +enum Behavior { + Ok, + Fault(ToolFault), + Hang, +} + +/// Scripted tool path: per tool name, a queue of behaviours; empty queue = ok. +struct Script { + queues: Mutex>>, + dispatches: AtomicUsize, +} + +impl Script { + fn new(entries: Vec<(&str, Vec)>) -> Arc { + Arc::new(Self { + queues: Mutex::new( + entries + .into_iter() + .map(|(k, v)| (k.to_string(), v.into())) + .collect(), + ), + dispatches: AtomicUsize::new(0), + }) + } + fn count(&self) -> usize { + self.dispatches.load(Ordering::SeqCst) + } +} + +#[async_trait] +impl ToolDispatcher for Script { + async fn dispatch( + &self, + skill_name: &str, + _arguments: &serde_json::Value, + ) -> Result { + self.dispatches.fetch_add(1, Ordering::SeqCst); + let next = self + .queues + .lock() + .unwrap() + .get_mut(skill_name) + .and_then(|q| q.pop_front()); + match next { + None | Some(Behavior::Ok) => Ok("ok".to_string()), + Some(Behavior::Fault(f)) => Err(f), + Some(Behavior::Hang) => { + tokio::time::sleep(Duration::from_secs(30)).await; + Ok("late".to_string()) + } + } + } +} + +fn engine(model: Arc, script: Arc