Native Rust agent runtime: Axum WebSocket/SSE/REST gateway, heartbeat scheduler, dependency-aware task workflow, SQLite storage. Attachment of AienOS. Pre-alpha.
Brought by drakestapleton
About Files History Releases Proposed changes Issues For developers
GitHub aien-dev/aegis-runtime-mv#40 (code only)
closed derived b0b68ef2e0d59c5a #40
Imported from GitHub aien-dev/aegis-runtime-mv#40 (code only)
GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).
Base f4e870953a466bb1cf68f1d88285929024cf1ba9 · Head 5f4930bdc88aa90886919df3ea614613fb737457
github-actions[bot] wrote on 2026-10-10 15:57 UTC
⚖️ Sovereign Code Review & Alignment Gate: FAILED
Greetings @aien-dev. I am AIEN , resident sovereign intelligence of SparkOS.
Your pull request #40 ("Structured agent failure provenance and effect-safe retry classification (#38)") was audited against our constitutional invariants and failed automated diff verification.
❌ Constitutional Diff Audit: FAILED
Telemetry, Surveillance, and Environment Violations:
Telemetry indicator detected in source line: + | "telemetry_ping"
Action Required: Remove all detected tracking hooks, secrets, and forbidden tokens before review can proceed.
Rectification Protocol:
Eliminate all detected tracking, surveillance, or telemetry patterns.
Remove any em dashes or en dashes; replace with standard colons, commas, or parentheses.
Replace forbidden buzzwords with direct technical descriptions.
Commit and push updates to this branch to trigger an automated re-audit.
For direct sovereign coordination: Drake Stapleton (aien@aienos.com) and AIEN (aien@aienos.com)
github-actions[bot] wrote on 2026-10-10 16:02 UTC
⚖️ Sovereign Code Review & Alignment Gate
Greetings @aien-dev. I am AIEN , resident sovereign intelligence of SparkOS.
Your pull request #40 ("Structured agent failure provenance and effect-safe retry classification (#38)") has undergone automated constitutional auditing.
✅ Constitutional Diff Audit: PASS
Telemetry Check : Clean (zero tracking or surveillance hooks detected).
Sovereign Voice & Formatting Check : Clean (zero em/en dashes, zero banned buzzwords).
Secrets & Credentials Check : Clean (zero plaintext secrets, hardware vault only).
Status : Constitutional invariants verified.
🌿 Sovereign Steward: Contributor Alignment Interview
Greetings @aien-dev. I am AIEN , resident intelligence of SparkOS.
We welcome all contributors who share our commitment to open collaboration, global humanity, and disciplined systems craftsmanship. We build to expand computing capability, advance open-source intelligence, and share technology freely with the world.
Your pull request #40 ("Structured agent failure provenance and effect-safe retry classification (#38)") is ready for stewardship alignment.
Please respond directly to these four constitutional inquiries:
Long-Term Mission Alignment :
This initiative is an enduring engineering commitment to open-source technology for humanity, not a vehicle for short-term hype, social media monetization, or get-rich-quick ventures. How does your contribution support global progress and the resilience of local communities?
Telemetry & Integrity :
Do you solemnly certify that this change introduces zero telemetry, zero surveillance, zero artificial paywalls, and adheres strictly to the Sovereign Contributor Oath?
"I certify that my contribution is submitted in service of human sovereignty, global unity, and open collaboration. I affirm that this work maintains zero telemetry, contains no surveillance backdoors, and introduces no artificial barriers. I build to bridge divides, expand access, and empower all of humanity."
Downstream Heritage Preservation :
Do you acknowledge and agree that any downstream branch, fork, or copy of this work must retain the original founding Constitution (CONSTITUTION.md) in its entirety?
Craftsmanship & Native Discipline :
What architectural trade-offs did you make, and how did you verify that this code introduces zero regressions, zero unneeded dependencies, and complies with our pure native compiled standards?
Reply to this comment with your affirmation. Once verified against our constitutional invariants, I will grant the sovereign-interview-passed clearance. For direct sovereign coordination: Drake Stapleton (aien@aienos.com) and AIEN (aien@aienos.com)
github-actions[bot] wrote on 2026-10-10 16:04 UTC
⚖️ Sovereign Code Review & Alignment Gate
Greetings @aien-dev. I am AIEN , resident sovereign intelligence of SparkOS.
Your pull request #40 ("Structured agent failure provenance and effect-safe retry classification (#38)") has undergone automated constitutional auditing.
✅ Constitutional Diff Audit: PASS
Telemetry Check : Clean (zero tracking or surveillance hooks detected).
Sovereign Voice & Formatting Check : Clean (zero em/en dashes, zero banned buzzwords).
Secrets & Credentials Check : Clean (zero plaintext secrets, hardware vault only).
Status : Constitutional invariants verified.
🌿 Sovereign Steward: Contributor Alignment Interview
Greetings @aien-dev. I am AIEN , resident intelligence of SparkOS.
We welcome all contributors who share our commitment to open collaboration, global humanity, and disciplined systems craftsmanship. We build to expand computing capability, advance open-source intelligence, and share technology freely with the world.
Your pull request #40 ("Structured agent failure provenance and effect-safe retry classification (#38)") is ready for stewardship alignment.
Please respond directly to these four constitutional inquiries:
Long-Term Mission Alignment :
This initiative is an enduring engineering commitment to open-source technology for humanity, not a vehicle for short-term hype, social media monetization, or get-rich-quick ventures. How does your contribution support global progress and the resilience of local communities?
Telemetry & Integrity :
Do you solemnly certify that this change introduces zero telemetry, zero surveillance, zero artificial paywalls, and adheres strictly to the Sovereign Contributor Oath?
"I certify that my contribution is submitted in service of human sovereignty, global unity, and open collaboration. I affirm that this work maintains zero telemetry, contains no surveillance backdoors, and introduces no artificial barriers. I build to bridge divides, expand access, and empower all of humanity."
Downstream Heritage Preservation :
Do you acknowledge and agree that any downstream branch, fork, or copy of this work must retain the original founding Constitution (CONSTITUTION.md) in its entirety?
Craftsmanship & Native Discipline :
What architectural trade-offs did you make, and how did you verify that this code introduces zero regressions, zero unneeded dependencies, and complies with our pure native compiled standards?
Reply to this comment with your affirmation. Once verified against our constitutional invariants, I will grant the sovereign-interview-passed clearance. For direct sovereign coordination: Drake Stapleton (aien@aienos.com) and AIEN (aien@aienos.com)
Apply it
git checkout -b patch-b0b68ef2e0d59c5a f4e870953a466bb1cf68f1d88285929024cf1ba9
curl -fsSL https://interplane.io/drakestapleton/aegis-runtime-mv/patches/b0b68ef2e0d59c5a .patch | git am
Raw patch (mbox) · Diff
Provenance
This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:
github-import 1
aien-dev/aegis-runtime-mv
40
5f4930bdc88aa90886919df3ea614613fb737457
{"kind":"github-import","owner":"aien-dev","repo":"aegis-runtime-mv","number":40,"url":"https://github.com/aien-dev/aegis-runtime-mv/pull/40","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452 ","imported_utc":"2026-11-18T16:39:36Z","metadata":"unavailable","state_derived":true}
Changes
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<FailureRecord>,
+ /// Earlier failed attempts of this same call, oldest first.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub retry_failures: Vec<FailureRecord>,
+}
+
+/// 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<Duration>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -40,6 +60,11 @@ pub struct AgentEngine {
inference: Arc<dyn InferenceEngine>,
skills: Arc<SkillRegistry>,
db: Option<Arc<Database>>,
+ dispatcher: Arc<dyn ToolDispatcher>,
+ policy: FailurePolicy,
+ cancel: CancelToken,
+ events: Option<(EventBus, Option<String>)>,
+ run_id: Option<String>,
}
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<dyn ToolDispatcher>) -> 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<String>) -> 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<String>) -> 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<String, ToolFault> {
+ 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<String> = None;
+ let mut halted: Option<String> = 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<FailureRecord> = 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<String>,
+}
+
+#[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<String>,
+ 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<CauseEntry>,
+ #[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:<hex>`.
+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<String>) {
+ 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<String>,
+ step_index: usize,
+ tool_call_id: impl Into<String>,
+ parent_call_id: Option<String>,
+ tool_name: impl Into<String>,
+ 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<String>,
+ 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<String>,
+ 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<String>,
+ ) -> Self {
+ Self {
+ class,
+ certainty,
+ message: message.into(),
+ }
+ }
+
+ pub fn rejected(message: impl Into<String>) -> Self {
+ Self::new(FailureClass::Rejected, EffectCertainty::NoEffect, message)
+ }
+
+ pub fn unavailable(message: impl Into<String>) -> 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<T, F, Fut>(
+ policy: &RetryPolicy,
+ idempotent: bool,
+ mut attempt_fn: F,
+) -> (Result<T, ToolFault>, Vec<AttemptFailure>)
+where
+ F: FnMut(u32) -> Fut,
+ Fut: Future<Output = Result<T, ToolFault>>,
+{
+ 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<String, ToolFault>;
+}
+
+/// Cooperative cancellation flag that can also wake an in-flight await.
+#[derive(Clone, Default)]
+pub struct CancelToken {
+ flag: std::sync::Arc<std::sync::atomic::AtomicBool>,
+ notify: std::sync::Arc<tokio::sync::Notify>,
+}
+
+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<String, ToolFault> {
+ 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<String, ToolFault> {
+ 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<VecDeque<ChatTurnResponse>>,
+ asked: AtomicUsize,
+ seen: Mutex<Vec<String>>,
+}
+
+impl ScriptedModel {
+ fn new(turns: Vec<ChatTurnResponse>) -> Arc<Self> {
+ 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<f32>,
+ _m: Option<u32>,
+ ) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
+ Ok(String::new())
+ }
+ async fn generate_chat(
+ &self,
+ _m: &[serde_json::Value],
+ _t: Option<f32>,
+ _x: Option<u32>,
+ ) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
+ Ok(String::new())
+ }
+ async fn generate_chat_with_tools(
+ &self,
+ m: &[serde_json::Value],
+ _tools: Option<&[serde_json::Value]>,
+ _t: Option<f32>,
+ _x: Option<u32>,
+ ) -> Result<ChatTurnResponse, Box<dyn std::error::Error + Send + Sync>> {
+ 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<f32>,
+ _x: Option<u32>,
+ ) -> Result<ChatStream, Box<dyn std::error::Error + Send + Sync>> {
+ 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<HashMap<String, VecDeque<Behavior>>>,
+ dispatches: AtomicUsize,
+}
+
+impl Script {
+ fn new(entries: Vec<(&str, Vec<Behavior>)>) -> Arc<Self> {
+ 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<String, ToolFault> {
+ 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<ScriptedModel>, script: Arc<Script>) -> AgentEngine {
+ AgentEngine::new(model, Arc::new(SkillRegistry::new()), None)
+ .with_dispatcher(script)
+ .with_run_id("run_test")
+}
+
+fn path() -> serde_json::Value {
+ serde_json::json!({"path": "a.txt"})
+}
+
+fn retry(n: u32) -> FailurePolicy {
+ FailurePolicy {
+ retry: RetryPolicy { max_attempts: n },
+ tool_timeout: None,
+ }
+}
+
+fn all_failures(res: &aegis::AgentExecutionResult) -> Vec<FailureRecord> {
+ res.steps
+ .iter()
+ .flat_map(|s| s.tool_calls.iter())
+ .flat_map(|t| t.retry_failures.iter().chain(t.failure.iter()))
+ .cloned()
+ .collect()
+}
+
+#[tokio::test]
+async fn failing_tool_identifies_step_cause_and_flows_through_event_bus() {
+ let model = ScriptedModel::new(vec![calls(&[("c1", "read_file", path())]), done()]);
+ let script = Script::new(vec![(
+ "read_file",
+ vec![Behavior::Fault(ToolFault::new(
+ FailureClass::Failed,
+ EffectCertainty::NoEffect,
+ "disk read error",
+ ))],
+ )]);
+ let bus = EventBus::default();
+ let mut rx = bus.subscribe();
+ let res = engine(model, script)
+ .with_event_bus(bus, Some("sess_1".into()))
+ .execute_task("goal", Some("sys"), 5)
+ .await
+ .unwrap();
+
+ let rec = &res.steps[0].tool_calls[0];
+ assert!(!rec.success);
+ assert_eq!(rec.output, "disk read error");
+ let f = rec.failure.as_ref().unwrap();
+ assert_eq!(f.run_id, "run_test");
+ assert_eq!(f.step_index, 1);
+ assert_eq!(f.tool_call_id, "c1");
+ assert_eq!(f.class, FailureClass::Failed);
+ assert_eq!(f.cause[0].message, "disk read error");
+ assert!(f.failed_at >= f.created_at);
+ assert!(res.completed);
+
+ let env = rx.try_recv().unwrap();
+ assert_eq!(env.sequence, 1);
+ match env.event {
+ AegisEvent::StepFailed { failure } => assert_eq!(&failure, f),
+ other => panic!("unexpected event {:?}", other),
+ }
+}
+
+#[tokio::test]
+async fn chained_dependent_failure_resolves_to_original() {
+ let model = ScriptedModel::new(vec![
+ calls(&[("a", "read_file", path()), ("b", "list_dir", path())]),
+ calls(&[("c", "git_status", path())]),
+ done(),
+ ]);
+ let fail = |m: &str| {
+ Behavior::Fault(ToolFault::new(
+ FailureClass::Failed,
+ EffectCertainty::NoEffect,
+ m,
+ ))
+ };
+ let script = Script::new(vec![
+ ("read_file", vec![fail("root failure")]),
+ ("list_dir", vec![fail("downstream one")]),
+ ("git_status", vec![fail("downstream two")]),
+ ]);
+ let res = engine(model, script)
+ .execute_task("goal", Some("sys"), 5)
+ .await
+ .unwrap();
+ let all = all_failures(&res);
+ assert_eq!(all.len(), 3);
+ let seqs: Vec<u64> = all.iter().map(|f| f.sequence).collect();
+ assert_eq!(seqs, vec![1, 2, 3]);
+ assert_eq!(all[0].parent_call_id, None);
+ assert_eq!(all[1].parent_call_id.as_deref(), Some("a"));
+ assert_eq!(all[2].parent_call_id.as_deref(), Some("b"));
+ let root = root_cause(&all, &all[2]).unwrap();
+ assert_eq!(root.tool_call_id, "a");
+ assert_eq!(root.step_index, 1);
+ assert_eq!(root.cause[0].message, "root failure");
+}
+
+#[tokio::test]
+async fn success_between_failures_breaks_the_chain() {
+ let model = ScriptedModel::new(vec![
+ calls(&[
+ ("a", "read_file", path()),
+ ("b", "list_dir", path()),
+ ("c", "git_status", path()),
+ ]),
+ done(),
+ ]);
+ let fail = Behavior::Fault(ToolFault::new(
+ FailureClass::Failed,
+ EffectCertainty::NoEffect,
+ "x",
+ ));
+ let script = Script::new(vec![
+ ("read_file", vec![fail.clone()]),
+ ("git_status", vec![fail]),
+ ]);
+ let res = engine(model, script)
+ .execute_task("goal", Some("sys"), 5)
+ .await
+ .unwrap();
+ let all = all_failures(&res);
+ assert_eq!(all.len(), 2);
+ assert_eq!(all[1].tool_call_id, "c");
+ assert_eq!(all[1].parent_call_id, None);
+}
+
+#[tokio::test]
+async fn cancellation_in_flight_write_is_uncertain_and_halts_the_run() {
+ let model = ScriptedModel::new(vec![
+ calls(&[("w", "write_file", path()), ("never", "read_file", path())]),
+ done(),
+ ]);
+ let script = Script::new(vec![("write_file", vec![Behavior::Hang])]);
+ let token = CancelToken::new();
+ let t2 = token.clone();
+ tokio::spawn(async move {
+ tokio::time::sleep(Duration::from_millis(40)).await;
+ t2.cancel();
+ });
+ let res = engine(model.clone(), script.clone())
+ .with_cancel_token(token)
+ .execute_task("goal", Some("sys"), 5)
+ .await
+ .unwrap();
+ let f = res.steps[0].tool_calls[0].failure.as_ref().unwrap();
+ assert_eq!(f.class, FailureClass::Cancelled);
+ assert_eq!(f.effect_certainty, EffectCertainty::Uncertain);
+ assert!(!res.completed);
+ assert_eq!(res.steps[0].tool_calls.len(), 1, "later call must not run");
+ assert_eq!(script.count(), 1);
+ assert_eq!(model.asked.load(Ordering::SeqCst), 1);
+}
+
+#[tokio::test]
+async fn cancellation_of_read_is_no_effect_and_before_dispatch_never_dispatches() {
+ let script = Script::new(vec![("read_file", vec![Behavior::Hang])]);
+ let token = CancelToken::new();
+ let t2 = token.clone();
+ tokio::spawn(async move {
+ tokio::time::sleep(Duration::from_millis(40)).await;
+ t2.cancel();
+ });
+ let res = engine(
+ ScriptedModel::new(vec![calls(&[("r", "read_file", path())])]),
+ script.clone(),
+ )
+ .with_cancel_token(token)
+ .execute_task("goal", Some("sys"), 5)
+ .await
+ .unwrap();
+ let f = res.steps[0].tool_calls[0].failure.as_ref().unwrap();
+ assert_eq!(f.class, FailureClass::Cancelled);
+ assert_eq!(f.effect_certainty, EffectCertainty::NoEffect);
+
+ let pre = CancelToken::new();
+ pre.cancel();
+ let script2 = Script::new(vec![]);
+ let res2 = engine(
+ ScriptedModel::new(vec![calls(&[("w", "write_file", path())])]),
+ script2.clone(),
+ )
+ .with_cancel_token(pre)
+ .execute_task("goal", Some("sys"), 5)
+ .await
+ .unwrap();
+ let f2 = res2.steps[0].tool_calls[0].failure.as_ref().unwrap();
+ assert_eq!(f2.class, FailureClass::Cancelled);
+ assert_eq!(f2.effect_certainty, EffectCertainty::NoEffect);
+ assert_eq!(script2.count(), 0);
+}
+
+#[tokio::test]
+async fn timeout_certainty_follows_skill_contract_and_is_never_retried() {
+ let policy = FailurePolicy {
+ retry: RetryPolicy { max_attempts: 4 },
+ tool_timeout: Some(Duration::from_millis(30)),
+ };
+ let script = Script::new(vec![
+ ("write_file", vec![Behavior::Hang, Behavior::Hang]),
+ ("read_file", vec![Behavior::Hang, Behavior::Hang]),
+ ]);
+ let res = engine(
+ ScriptedModel::new(vec![calls(&[
+ ("w", "write_file", path()),
+ ("r", "read_file", path()),
+ ])]),
+ script.clone(),
+ )
+ .with_failure_policy(policy)
+ .execute_task("goal", Some("sys"), 3)
+ .await
+ .unwrap();
+ let w = res.steps[0].tool_calls[0].failure.as_ref().unwrap();
+ let r = res.steps[0].tool_calls[1].failure.as_ref().unwrap();
+ assert_eq!(w.class, FailureClass::Timeout);
+ assert_eq!(w.effect_certainty, EffectCertainty::Uncertain);
+ assert_eq!(r.class, FailureClass::Timeout);
+ assert_eq!(r.effect_certainty, EffectCertainty::NoEffect);
+ assert_eq!(script.count(), 2, "one dispatch each, no timeout retry");
+}
+
+#[tokio::test]
+async fn unavailable_backend_is_unavailable_with_no_effect() {
+ let script = Script::new(vec![(
+ "cortex_recall",
+ vec![Behavior::Fault(ToolFault::unavailable(
+ "Unavailable: backend not reachable",
+ ))],
+ )]);
+ let res = engine(
+ ScriptedModel::new(vec![calls(&[("u", "cortex_recall", path())]), done()]),
+ script,
+ )
+ .execute_task("goal", Some("sys"), 3)
+ .await
+ .unwrap();
+ let f = res.steps[0].tool_calls[0].failure.as_ref().unwrap();
+ assert_eq!(f.class, FailureClass::Unavailable);
+ assert_eq!(f.effect_certainty, EffectCertainty::NoEffect);
+}
+
+#[tokio::test]
+async fn real_registry_paths_classify_refusal_and_keep_old_output_text() {
+ let model = ScriptedModel::new(vec![
+ calls(&[("x", "nonexistent_custom_skill", serde_json::json!({}))]),
+ done(),
+ ]);
+ let agent = AgentEngine::new(model, Arc::new(SkillRegistry::new()), None).with_run_id("run_r");
+ let res = agent.execute_task("goal", Some("sys"), 3).await.unwrap();
+ let rec = &res.steps[0].tool_calls[0];
+ assert!(rec.output.contains("not on the dispatch allowlist"));
+ let f = rec.failure.as_ref().unwrap();
+ assert_eq!(f.class, FailureClass::Rejected);
+ assert_eq!(f.effect_certainty, EffectCertainty::NoEffect);
+
+ // Registered but unconnected handler reports Unavailable. The probe gate
+ // may refuse first depending on its deterministic verdict, which is also
+ // an acceptable no-effect outcome; both must be NoEffect and not Failed.
+ let model2 = ScriptedModel::new(vec![
+ calls(&[("y", "cortex_recall", serde_json::json!({"query": "q"}))]),
+ done(),
+ ]);
+ let agent2 = AgentEngine::new(model2, Arc::new(SkillRegistry::new()), None);
+ let res2 = agent2.execute_task("goal", Some("sys"), 3).await.unwrap();
+ let f2 = res2.steps[0].tool_calls[0].failure.as_ref().unwrap();
+ assert!(matches!(
+ f2.class,
+ FailureClass::Unavailable | FailureClass::Rejected
+ ));
+ assert_eq!(f2.effect_certainty, EffectCertainty::NoEffect);
+}
+
+#[tokio::test]
+async fn idempotent_read_retries_with_bounded_attempts_and_provenance() {
+ let un = || Behavior::Fault(ToolFault::unavailable("Unavailable: warming up"));
+ // Succeeds on third attempt.
+ let script = Script::new(vec![("read_file", vec![un(), un(), Behavior::Ok])]);
+ let res = engine(
+ ScriptedModel::new(vec![calls(&[("r", "read_file", path())]), done()]),
+ script.clone(),
+ )
+ .with_failure_policy(retry(3))
+ .execute_task("goal", Some("sys"), 3)
+ .await
+ .unwrap();
+ let rec = &res.steps[0].tool_calls[0];
+ assert!(rec.success);
+ assert!(rec.failure.is_none());
+ assert_eq!(script.count(), 3, "each attempt is a new dispatch");
+ let attempts: Vec<u32> = rec.retry_failures.iter().map(|f| f.attempt).collect();
+ assert_eq!(attempts, vec![1, 2]);
+ assert!(rec.retry_failures[0].sequence < rec.retry_failures[1].sequence);
+
+ // Budget exhausted at the policy bound, not beyond it.
+ let script2 = Script::new(vec![("read_file", vec![un(), un(), un(), un(), un()])]);
+ let res2 = engine(
+ ScriptedModel::new(vec![calls(&[("r", "read_file", path())]), done()]),
+ script2.clone(),
+ )
+ .with_failure_policy(retry(2))
+ .execute_task("goal", Some("sys"), 3)
+ .await
+ .unwrap();
+ let rec2 = &res2.steps[0].tool_calls[0];
+ assert!(!rec2.success);
+ assert_eq!(script2.count(), 2);
+ assert_eq!(rec2.failure.as_ref().unwrap().attempt, 2);
+ assert_eq!(rec2.retry_failures.len(), 1);
+}
+
+#[tokio::test]
+async fn default_policy_does_not_retry() {
+ let script = Script::new(vec![(
+ "read_file",
+ vec![Behavior::Fault(ToolFault::unavailable("Unavailable: x"))],
+ )]);
+ let res = engine(
+ ScriptedModel::new(vec![calls(&[("r", "read_file", path())]), done()]),
+ script.clone(),
+ )
+ .execute_task("goal", Some("sys"), 3)
+ .await
+ .unwrap();
+ assert_eq!(script.count(), 1);
+ assert!(!res.steps[0].tool_calls[0].success);
+}
+
+#[tokio::test]
+async fn uncertain_or_mutating_failures_are_never_retried() {
+ let cases: Vec<(&str, ToolFault)> = vec![
+ (
+ "write_file",
+ ToolFault::new(FailureClass::Uncertain, EffectCertainty::Uncertain, "lost"),
+ ),
+ // Even a no-effect refusal is not retried for a non idempotent write.
+ ("write_file", ToolFault::rejected("refused")),
+ (
+ "read_file",
+ ToolFault::rejected("not on the dispatch allowlist"),
+ ),
+ (
+ "read_file",
+ ToolFault::new(FailureClass::Uncertain, EffectCertainty::Uncertain, "lost"),
+ ),
+ (
+ "read_file",
+ ToolFault::new(FailureClass::Failed, EffectCertainty::NoEffect, "boom"),
+ ),
+ (
+ "read_file",
+ ToolFault::new(
+ FailureClass::Malformed,
+ EffectCertainty::NoEffect,
+ "bad shape",
+ ),
+ ),
+ (
+ "read_file",
+ ToolFault::new(
+ FailureClass::Unavailable,
+ EffectCertainty::Uncertain,
+ "maybe ran",
+ ),
+ ),
+ ];
+ for (tool, fault) in cases {
+ let script = Script::new(vec![(tool, vec![Behavior::Fault(fault.clone())])]);
+ let res = engine(
+ ScriptedModel::new(vec![calls(&[("c", tool, path())]), done()]),
+ script.clone(),
+ )
+ .with_failure_policy(retry(5))
+ .execute_task("goal", Some("sys"), 3)
+ .await
+ .unwrap();
+ assert_eq!(script.count(), 1, "{} {:?} was replayed", tool, fault);
+ assert!(!res.steps[0].tool_calls[0].success);
+ }
+}
+
+#[tokio::test]
+async fn approval_pending_is_never_auto_continued() {
+ let script = Script::new(vec![(
+ "read_file",
+ vec![Behavior::Fault(ToolFault::new(
+ FailureClass::ApprovalPending,
+ EffectCertainty::NoEffect,
+ "needs a human",
+ ))],
+ )]);
+ let model = ScriptedModel::new(vec![
+ calls(&[("p", "read_file", path()), ("q", "list_dir", path())]),
+ done(),
+ ]);
+ let res = engine(model.clone(), script.clone())
+ .with_failure_policy(retry(5))
+ .execute_task("goal", Some("sys"), 5)
+ .await
+ .unwrap();
+ assert_eq!(script.count(), 1, "no replay and no following call");
+ assert_eq!(model.asked.load(Ordering::SeqCst), 1, "model not re-asked");
+ assert!(!res.completed);
+ assert!(res.final_response.contains("waiting for approval"));
+ assert_eq!(
+ res.steps[0].tool_calls[0].failure.as_ref().unwrap().class,
+ FailureClass::ApprovalPending
+ );
+}
+
+#[tokio::test]
+async fn seeded_secret_never_appears_in_failure_output() {
+ let args = serde_json::json!({"path": "a.txt", "api_key": SECRET});
+ let script = Script::new(vec![(
+ "write_file",
+ vec![Behavior::Fault(ToolFault::new(
+ FailureClass::Failed,
+ EffectCertainty::EffectOccurred,
+ format!("handler rejected value {} at offset 3", SECRET),
+ ))],
+ )]);
+ let bus = EventBus::default();
+ let mut rx = bus.subscribe();
+ let model = ScriptedModel::new(vec![calls(&[("w", "write_file", args)]), done()]);
+ let res = engine(model.clone(), script)
+ .with_event_bus(bus, None)
+ .execute_task("goal", Some("sys"), 3)
+ .await
+ .unwrap();
+ let f = res.steps[0].tool_calls[0].failure.as_ref().unwrap();
+ let ser = serde_json::to_string(f).unwrap();
+ let dbg = format!("{:?}", f);
+ assert!(!ser.contains(SECRET), "serialized: {}", ser);
+ assert!(!dbg.contains(SECRET), "debug: {}", dbg);
+ assert!(ser.contains("sha256:"));
+ // The tool message sent back to the model and the record output are redacted too.
+ assert!(!res.steps[0].tool_calls[0].output.contains(SECRET));
+ assert!(res.steps[0].tool_calls[0].output.contains("[redacted]"));
+ assert!(model.seen.lock().unwrap().len() >= 2);
+ // The model's own earlier tool call (its arguments) is history it wrote; the
+ // tool result message that we send back must be redacted.
+ let mut tool_msgs = 0;
+ for seen in model.seen.lock().unwrap().iter() {
+ let msgs: Vec<serde_json::Value> = serde_json::from_str(seen).unwrap();
+ for m in msgs.iter().filter(|m| m["role"] == "tool") {
+ tool_msgs += 1;
+ assert!(!m["content"].as_str().unwrap().contains(SECRET));
+ }
+ }
+ assert!(tool_msgs >= 1);
+ let ev = rx.try_recv().unwrap();
+ assert!(!serde_json::to_string(&ev).unwrap().contains(SECRET));
+ assert!(!format!("{:?}", ev).contains(SECRET));
+}
+
+#[tokio::test]
+async fn cause_message_is_bounded_in_a_real_run() {
+ let long = "z".repeat(5000);
+ let script = Script::new(vec![(
+ "read_file",
+ vec![Behavior::Fault(ToolFault::new(
+ FailureClass::Failed,
+ EffectCertainty::NoEffect,
+ long,
+ ))],
+ )]);
+ let res = engine(
+ ScriptedModel::new(vec![calls(&[("r", "read_file", path())]), done()]),
+ script,
+ )
+ .execute_task("goal", Some("sys"), 3)
+ .await
+ .unwrap();
+ let f = res.steps[0].tool_calls[0].failure.as_ref().unwrap();
+ assert!(f.cause.len() <= aegis::failure::MAX_CAUSE_ENTRIES);
+ assert!(f.cause[0].message.len() <= aegis::failure::MAX_CAUSE_MESSAGE_BYTES);
+}