diff --git a/.crumb b/.crumb index 9559f67..78881c4 100644 --- a/.crumb +++ b/.crumb @@ -25,8 +25,8 @@ "generated": { "children": [ { - "digest": "2d3aba84ec7059283089a3519c36336e7d148cbaffe44e02a6423c6c00303126", - "last_commit": "945a63f", + "digest": "0e67f750d69e5210c482d53230ffe07209af58a7d6176eb6a936759c0504d4c6", + "last_commit": "e21dab3", "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": "abb952194a8ed23126dc8163ce4697adab26469a76f1945838adb525cc09017a", + "last_commit": "8cba4a8", "name": "src", "purpose": "Directory src. Purpose not yet described by a human." }, { - "digest": "f4bd4396bc580ae13307cfae0811c25db094a9c1b1a5ec06c094f19e20ae6382", - "last_commit": "7288fa6", + "digest": "df847e5d91ae7ee6ec75ad9abc538714dc43f89449684f8827b09a6108ea0d2e", + "last_commit": "e21dab3", "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:40c5a9c14dc005adbcf61c63a2217d0da1e551b9fe6368b2103b490c3226935e", + "compiled_at": "2026-10-10T16:05:01Z", "compiler": "crumb-compile/1", - "digest": "sha256:a42b63d14ccc0ee65dedc65f301ab010a62f50f42dabfb6cc68644a496d3ebc4", + "digest": "sha256:a3483fe46887a8829bc847c0b1f129fb54e9ea2fe3ca2cb0e73001b8a6115ae0", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 77, - "generated_at_commit": "7288fa65b22fe45e36a88f44150f21ed8781dc89", - "source_tree": "sha256:3e4f0004ac330c64ebd2a405c3ee1d3cc5d5c0b8e129d3b58d50f7106c572391" + "files": 83, + "generated_at_commit": "e21dab3edbdededb2396a74d0614c797b912bb6a", + "source_tree": "sha256:79fe2cae789343782218006056cd3f7f27d80620de55a9c2107e3de7a744f76a" }, "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..e30bbbd 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:05:01Z", "compiler": "crumb-compile/1", - "digest": "sha256:2d3aba84ec7059283089a3519c36336e7d148cbaffe44e02a6423c6c00303126", + "digest": "sha256:0e67f750d69e5210c482d53230ffe07209af58a7d6176eb6a936759c0504d4c6", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 1, - "generated_at_commit": "7288fa65b22fe45e36a88f44150f21ed8781dc89", - "source_tree": "sha256:542eaba79ea3db3c1c44dafc78c0ccfacaecb99eaf630dd2beaf33dd4c78584d" + "files": 3, + "generated_at_commit": "e21dab3edbdededb2396a74d0614c797b912bb6a", + "source_tree": "sha256:6a89e2f26e44220fe9335f8be611fac690c78f656d1f6bd0b88359f98a91ed85" }, "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/docs/WORKFLOW-DAG.md b/docs/WORKFLOW-DAG.md new file mode 100644 index 0000000..023cb82 --- /dev/null +++ b/docs/WORKFLOW-DAG.md @@ -0,0 +1,58 @@ +# Workflow DAG (issue #39) + +A small dependency-aware task layer for multi-step agent work. It decides +when a caller-supplied task may start. Nothing else. + +## Existing machinery + +Inspected before writing any code. + +| Area | What exists | +|---|---| +| `src/orchestration/run.rs` | One `Run` with `RunState {Running, WaitingForApproval, WaitingForTool, Completed, Failed, Cancelled}`, step and action counters, a `Trigger`. A run is a single linear lifecycle. | +| `src/orchestration/budget.rs` | `RunBudget` counters (steps, inference calls, actions, wall seconds) for one run. | +| `src/orchestration/termination.rs`, `trigger.rs` | Why a run ended; what started it. | +| `src/agent.rs` | `AgentEngine::execute_task`: a sequential model/tool loop. Since #38 it classifies tool failures (`FailureRecord`), retries only idempotent no-effect cases, and stops on `ApprovalPending`. | +| `src/failure.rs` (#38) | `FailureClass`, `EffectCertainty`, `FailureRecord`, `CancelToken`. Reused here. | +| `src/events/{event,envelope,bus}.rs` | `AegisEvent`, `EventEnvelope` (has a `sequence` field), broadcast `EventBus`. | +| `src/execution/{broker,action,receipt}.rs` | `ExecutionAuthority` and action receipts: the only authority for effects. | +| `src/sessions`, `tests/aegis_tests.rs` | Ids (`RunId`, `SessionId`), stores, and the integration test conventions (tokio tests, scripted fakes). | + +Already present: the single-run lifecycle, approval-gate states, a per-run budget, cancellation tokens, failure vocabulary, events. + +Absent before this change: prerequisite edges between tasks, readiness tracking, bounded concurrent execution of independent tasks, propagation of a prerequisite's failure to dependents, a workflow-level event order. No equivalent DAG exists, so `src/orchestration/workflow.rs` is new. It is not an inference scheduler: AIEN's `aien-scheduler` and the swarm manager are untouched and never called. + +## Model + +- `TaskId` newtype. `WorkflowSpec::builder().add_task(id, &[deps], runner)...build()` rejects empty ids, duplicate tasks, duplicate edges, self dependency, unknown predecessors and cycles with typed `WorkflowError`. +- `TaskState {Pending, Ready, Running, WaitingForApproval, Completed, Failed(FailureRecord), Cancelled, Skipped{prerequisite}}`. +- `TaskRunner` is the task body and returns `TaskOutcome {Completed(value), Failed(ToolFault), ApprovalPending, Cancelled}`. `certainty_on_interrupt()` says what is known about effects if the DAG interrupts the body (timeout, cancel); the default is `Uncertain`. +- `WorkflowConfig {run_id, session_id, max_parallel, per_task_timeout, total_budget}`. + +## Rules the executor enforces + +- A dependent becomes Ready only when every prerequisite is `Completed`. +- A prerequisite that is `Failed`, `Cancelled` or `Skipped` makes the dependent `Skipped` with a `FailureRecord` of class `Rejected`, certainty `NoEffect`, cause `prerequisite failed: `. This is transitive. +- `WaitingForApproval` is not success and not terminal. Dependents stay `Pending`; the report lists them in `unfinished` and the status is `WaitingForApproval`. +- The DAG never retries or reschedules anything. An `Uncertain` outcome runs once and is final. +- Timeout gives `Failed` with class `Timeout` and the runner's certainty. Cancellation (token or total budget) cancels running tasks and every Pending/Ready task and starts nothing new. +- Parallelism is bounded by a `tokio::sync::Semaphore`. The coordinator only awaits; task bodies run on spawned tasks. No `block_on`. +- The DAG authorizes nothing and caches no decision. Real effects go through the agent/skill gate path or `ExecutionAuthority` inside the task body. + +## Events and replay + +Every transition takes a workflow sequence number under one lock, together with the state change, and is published in that same critical section. New `AegisEvent` variants: `WorkflowTaskReady/Started/Completed/Waiting/Failed/Cancelled/Skipped`, `WorkflowFinished`. They carry `workflow_seq` and go out with `EventEnvelope.sequence` set to it, so sorting by sequence replays the exact order. With `max_parallel = 1` the whole order is fixed for a given spec; with more parallelism the order of simultaneous completions follows real completion order, but the sequence is still gapless and dependency-consistent. Existing variants are unchanged; the canonical mapping returns `None` for the new ones. + +Results: `WorkflowSnapshot.results` maps task id to a sha256 digest of the result value. Failure records for Failed, Skipped and Cancelled tasks are in `WorkflowReport.failures`. + +## Agent adapter + +`AgentTaskRunner` runs one `AgentEngine::execute_task` as a task; `agent_outcome` maps its result (failure class and certainty from the last tool failure, `ApprovalPending` stays pending, an incomplete run is `Failed/Uncertain`). It is a thin seam and is not exercised against a live model in tests. + +## Restart boundary + +Workflow state is in memory only. After a process restart nothing is recovered and no task is resumed or re-run. `WorkflowSnapshot` is serializable (tested) so a later change can persist it, but no schema, table or recovery path exists. A resumed workflow must not re-run a task whose effect is `Uncertain`; that recovery policy is not designed here. + +## Not claimed + +AEGIS is outside release v1; nothing here is wired into a release path or the frozen E2E contract. Timings printed by the demo test compare `max_parallel = 1` against 2 with sleep-based fake tasks on CPU. They are informational, and no GPU or throughput claim is made. diff --git a/src/.crumb b/src/.crumb index a56801e..00a4ebe 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": "14dd72b905c79d44b86b01f4ab43763cf21520fd4e38f077b682e35268010d17", + "last_commit": "8cba4a8", "name": "events", "purpose": "Directory src/events. Purpose not yet described by a human." }, @@ -51,8 +51,8 @@ "purpose": "Directory src/execution. Purpose not yet described by a human." }, { - "digest": "0c08369b428afac636246de8b36637a58106c235df8524f3f01be1195cc70dbe", - "last_commit": "1b0c299", + "digest": "2f0cb472c464c96c0c999130c8462db46bbeaf6a8b1d770ff2ff502e24b84500", + "last_commit": "8cba4a8", "name": "orchestration", "purpose": "Directory src/orchestration. 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:a59ed6eb87f1c402e863353ec922d5962090251ec943c0389b96c1ffa11a5a8e", + "compiled_at": "2026-10-10T16:05:01Z", "compiler": "crumb-compile/1", - "digest": "sha256:7cbd75ce692a5afecfdd4b37eb4fbd0bff7fb69fd6672988a859b7ea3bf7a121", + "digest": "sha256:abb952194a8ed23126dc8163ce4697adab26469a76f1945838adb525cc09017a", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 47, - "generated_at_commit": "7288fa65b22fe45e36a88f44150f21ed8781dc89", - "source_tree": "sha256:14c10750aceaae8190f5e23582515fd168cf6e543aa376920cef16c95a1ed8de" + "files": 49, + "generated_at_commit": "e21dab3edbdededb2396a74d0614c797b912bb6a", + "source_tree": "sha256:cbff5b20541baaf2bbd1db819692230be1d361a6ff77a3c4610847c5a62a47d2" }, "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..231ad39 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-10T16:05:01Z", "compiler": "crumb-compile/1", - "digest": "sha256:e30659e60d0a3efae1eb9bc4a0054bacb2656ff8456c000e4e9870b06378ddfd", + "digest": "sha256:14dd72b905c79d44b86b01f4ab43763cf21520fd4e38f077b682e35268010d17", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 5, - "generated_at_commit": "7288fa65b22fe45e36a88f44150f21ed8781dc89", - "source_tree": "sha256:524f9a53c8a46430330937f899070bef32d392944ca6e3d38c3f27886bbc2fa6" + "generated_at_commit": "e21dab3edbdededb2396a74d0614c797b912bb6a", + "source_tree": "sha256:559178d9f324b485ea60b2c5633cae9bcaa92b50f320b9ec3b7a6130230abef2" }, "owner_lane": "", "seed": { diff --git a/src/events/event.rs b/src/events/event.rs index 3ccb0b9..9862e74 100644 --- a/src/events/event.rs +++ b/src/events/event.rs @@ -30,6 +30,58 @@ 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, + }, + + /// Workflow (task DAG) transitions. `workflow_seq` is assigned under one + /// lock at transition time, so sorting by it replays the exact order. + WorkflowTaskReady { + run_id: String, + workflow_seq: u64, + task_id: String, + }, + WorkflowTaskStarted { + run_id: String, + workflow_seq: u64, + task_id: String, + }, + WorkflowTaskCompleted { + run_id: String, + workflow_seq: u64, + task_id: String, + result_digest: String, + }, + WorkflowTaskWaiting { + run_id: String, + workflow_seq: u64, + task_id: String, + }, + WorkflowTaskFailed { + run_id: String, + workflow_seq: u64, + task_id: String, + failure: crate::failure::FailureRecord, + }, + WorkflowTaskCancelled { + run_id: String, + workflow_seq: u64, + task_id: String, + }, + WorkflowTaskSkipped { + run_id: String, + workflow_seq: u64, + task_id: String, + prerequisite: String, + }, + WorkflowFinished { + run_id: String, + workflow_seq: u64, + status: String, + }, + 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..fba5b92 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::{ @@ -26,6 +32,10 @@ pub use inference::{ ProtocolInferenceBackend, ToolCallFunction, ToolCallItem, }; pub use mojo_bridge::MojoSimdBridge; +pub use orchestration::workflow::{ + TaskId, TaskOutcome, TaskRunner, TaskState, WorkflowConfig, WorkflowError, WorkflowExecutor, + WorkflowReport, WorkflowSpec, WorkflowStatus, +}; pub use orchestration::{Run, RunBudget, RunState, TerminationReason, Trigger}; pub use persistence::{ AsyncDatabase, CrumbRecord, Database, PersistenceError, SqliteActionStore, SqliteApprovalStore, diff --git a/src/orchestration/.crumb b/src/orchestration/.crumb index fe21733..89d9399 100644 --- a/src/orchestration/.crumb +++ b/src/orchestration/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-04T18:13:51Z", + "compiled_at": "2026-10-10T16:05:01Z", "compiler": "crumb-compile/1", - "digest": "sha256:0c08369b428afac636246de8b36637a58106c235df8524f3f01be1195cc70dbe", + "digest": "sha256:2f0cb472c464c96c0c999130c8462db46bbeaf6a8b1d770ff2ff502e24b84500", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 5, - "generated_at_commit": "7288fa65b22fe45e36a88f44150f21ed8781dc89", - "source_tree": "sha256:b0e17001d12b6199a624eca29181527851108d5157f2460ea610a4e4074a0f10" + "files": 6, + "generated_at_commit": "e21dab3edbdededb2396a74d0614c797b912bb6a", + "source_tree": "sha256:a348ca8c11e634e65edf319e0d659df6d1fa70fd32a1ace49ff38e167dab98a3" }, "owner_lane": "", "seed": { diff --git a/src/orchestration/mod.rs b/src/orchestration/mod.rs index 9979a63..47d90e2 100644 --- a/src/orchestration/mod.rs +++ b/src/orchestration/mod.rs @@ -2,6 +2,7 @@ pub mod budget; pub mod run; pub mod termination; pub mod trigger; +pub mod workflow; pub use budget::RunBudget; pub use run::{Run, RunState}; diff --git a/src/orchestration/workflow.rs b/src/orchestration/workflow.rs new file mode 100644 index 0000000..f57223b --- /dev/null +++ b/src/orchestration/workflow.rs @@ -0,0 +1,961 @@ +//! Dependency-aware task workflow (DAG) for multi-step agent work (issue #39). +//! +//! This layer sits above the single-run lifecycle in `orchestration::run` and +//! far above AIEN inference scheduling. It decides only WHEN a caller-supplied +//! task may start. It authorizes nothing, caches no decision, retries nothing +//! and never schedules inference: every real effect happens inside the task +//! body through the existing gated paths. State is in memory only and does not +//! survive a restart (see `docs/WORKFLOW-DAG.md`). + +use crate::events::{AegisEvent, EventBus, EventEnvelope}; +use crate::failure::{ + now_millis, payload_digest, CancelToken, EffectCertainty, FailureClass, FailureRecord, + ToolFault, +}; +use crate::sessions::id::{RunId, SessionId}; +use async_trait::async_trait; +use futures_util::future::BoxFuture; +use parking_lot::Mutex; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::fmt; +use std::sync::Arc; +use std::time::Duration; +use tokio::sync::Semaphore; +use tokio::task::JoinSet; + +/// Tool name stamped on failure records produced by the DAG itself. +pub const WORKFLOW_TOOL_NAME: &str = "workflow_task"; + +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(transparent)] +pub struct TaskId(String); + +impl TaskId { + pub fn new(id: impl Into) -> Self { + Self(id.into()) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl fmt::Display for TaskId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl From<&str> for TaskId { + fn from(s: &str) -> Self { + Self::new(s) + } +} + +/// Build-time errors. A spec that builds is a valid DAG. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum WorkflowError { + EmptyTaskId, + DuplicateTask(TaskId), + UnknownPredecessor { + task: TaskId, + predecessor: TaskId, + }, + DuplicateEdge { + task: TaskId, + predecessor: TaskId, + }, + SelfDependency(TaskId), + /// One cycle, listed in dependency order. + Cycle(Vec), + InvalidConfig(String), +} + +impl fmt::Display for WorkflowError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::EmptyTaskId => write!(f, "task id must not be empty"), + Self::DuplicateTask(t) => write!(f, "duplicate task id: {t}"), + Self::UnknownPredecessor { task, predecessor } => { + write!(f, "task {task} depends on unknown task {predecessor}") + } + Self::DuplicateEdge { task, predecessor } => { + write!(f, "task {task} lists predecessor {predecessor} twice") + } + Self::SelfDependency(t) => write!(f, "task {t} depends on itself"), + Self::Cycle(c) => { + let names: Vec<&str> = c.iter().map(|t| t.as_str()).collect(); + write!(f, "dependency cycle: {}", names.join(" -> ")) + } + Self::InvalidConfig(m) => write!(f, "invalid workflow config: {m}"), + } + } +} + +impl std::error::Error for WorkflowError {} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "state", content = "detail", rename_all = "snake_case")] +pub enum TaskState { + Pending, + Ready, + Running, + WaitingForApproval, + Completed, + Failed(FailureRecord), + Cancelled, + Skipped { prerequisite: TaskId }, +} + +impl TaskState { + /// Terminal means the task will never change state again. + pub fn is_terminal(&self) -> bool { + matches!( + self, + Self::Completed | Self::Failed(_) | Self::Cancelled | Self::Skipped { .. } + ) + } + + /// Short stable name, used in events. + pub fn name(&self) -> &'static str { + match self { + Self::Pending => "pending", + Self::Ready => "ready", + Self::Running => "running", + Self::WaitingForApproval => "waiting_for_approval", + Self::Completed => "completed", + Self::Failed(_) => "failed", + Self::Cancelled => "cancelled", + Self::Skipped { .. } => "skipped", + } + } +} + +/// What a task body reports. Approval pending is not success. +#[derive(Debug, Clone)] +pub enum TaskOutcome { + Completed(serde_json::Value), + Failed(ToolFault), + ApprovalPending, + Cancelled, +} + +/// Handed to the task body when it starts. +#[derive(Clone)] +pub struct TaskContext { + pub task_id: TaskId, + pub run_id: RunId, + pub session_id: SessionId, + /// Fires when the workflow is cancelled or its total budget is spent. + pub cancel: CancelToken, +} + +/// Caller-supplied task body. It must route every real effect through the +/// existing gate path; the DAG never authorizes on its behalf. +#[async_trait] +pub trait TaskRunner: Send + Sync { + async fn run(&self, ctx: TaskContext) -> TaskOutcome; + + /// Certainty recorded when the DAG interrupts this task (timeout or + /// cancellation) before it reports. Default is the safe answer. + fn certainty_on_interrupt(&self) -> EffectCertainty { + EffectCertainty::Uncertain + } +} + +/// Wraps an async closure as a `TaskRunner`. +pub struct FnRunner { + f: F, + interrupt: EffectCertainty, +} + +pub fn runner_fn(f: F) -> Arc +where + F: Fn(TaskContext) -> BoxFuture<'static, TaskOutcome> + Send + Sync + 'static, +{ + Arc::new(FnRunner { + f, + interrupt: EffectCertainty::Uncertain, + }) +} + +/// Like `runner_fn` with an explicit certainty for interruptions. +pub fn runner_fn_with_certainty(f: F, interrupt: EffectCertainty) -> Arc +where + F: Fn(TaskContext) -> BoxFuture<'static, TaskOutcome> + Send + Sync + 'static, +{ + Arc::new(FnRunner { f, interrupt }) +} + +#[async_trait] +impl TaskRunner for FnRunner +where + F: Fn(TaskContext) -> BoxFuture<'static, TaskOutcome> + Send + Sync + 'static, +{ + async fn run(&self, ctx: TaskContext) -> TaskOutcome { + (self.f)(ctx).await + } + + fn certainty_on_interrupt(&self) -> EffectCertainty { + self.interrupt + } +} + +struct TaskNode { + id: TaskId, + deps: Vec, + runner: Arc, +} + +/// A validated DAG. Insertion order is the deterministic tie break. +pub struct WorkflowSpec { + tasks: Vec, +} + +impl WorkflowSpec { + pub fn builder() -> WorkflowBuilder { + WorkflowBuilder::default() + } + + pub fn task_ids(&self) -> Vec { + self.tasks.iter().map(|t| t.id.clone()).collect() + } + + pub fn len(&self) -> usize { + self.tasks.len() + } + + pub fn is_empty(&self) -> bool { + self.tasks.is_empty() + } +} + +#[derive(Default)] +pub struct WorkflowBuilder { + tasks: Vec, +} + +impl WorkflowBuilder { + /// Predecessors must already be added, which also makes forward edges + /// (and so most cycles) impossible; `build` still checks the whole graph. + pub fn add_task( + mut self, + id: impl Into, + deps: &[&str], + runner: Arc, + ) -> Result { + let id = id.into(); + if id.as_str().is_empty() { + return Err(WorkflowError::EmptyTaskId); + } + if self.tasks.iter().any(|t| t.id == id) { + return Err(WorkflowError::DuplicateTask(id)); + } + let mut seen: HashSet<&str> = HashSet::new(); + let mut deps_out = Vec::with_capacity(deps.len()); + for d in deps { + if *d == id.as_str() { + return Err(WorkflowError::SelfDependency(id)); + } + if !seen.insert(d) { + return Err(WorkflowError::DuplicateEdge { + task: id, + predecessor: TaskId::new(*d), + }); + } + deps_out.push(TaskId::new(*d)); + } + self.tasks.push(TaskNode { + id, + deps: deps_out, + runner, + }); + Ok(self) + } + + /// Validates predecessors and rejects cycles. Predecessors may be added + /// after their dependents, so this is where unknown ids and cycles surface. + pub fn build(self) -> Result { + let index: HashMap<&TaskId, usize> = self + .tasks + .iter() + .enumerate() + .map(|(i, t)| (&t.id, i)) + .collect(); + for t in &self.tasks { + for d in &t.deps { + if !index.contains_key(d) { + return Err(WorkflowError::UnknownPredecessor { + task: t.id.clone(), + predecessor: d.clone(), + }); + } + } + } + // Kahn: whatever cannot be peeled off sits on or behind a cycle. + let mut indegree: Vec = self.tasks.iter().map(|t| t.deps.len()).collect(); + let mut queue: Vec = (0..self.tasks.len()) + .filter(|i| indegree[*i] == 0) + .collect(); + let mut peeled = 0; + while let Some(n) = queue.pop() { + peeled += 1; + for (i, t) in self.tasks.iter().enumerate() { + if t.deps.contains(&self.tasks[n].id) { + indegree[i] -= 1; + if indegree[i] == 0 { + queue.push(i); + } + } + } + } + if peeled != self.tasks.len() { + return Err(WorkflowError::Cycle(find_cycle( + &self.tasks, + &index, + &indegree, + ))); + } + Ok(WorkflowSpec { tasks: self.tasks }) + } +} + +/// Walks predecessor links among the unpeeled nodes until one repeats. +fn find_cycle( + tasks: &[TaskNode], + index: &HashMap<&TaskId, usize>, + indegree: &[usize], +) -> Vec { + let start = (0..tasks.len()).find(|i| indegree[*i] > 0).unwrap_or(0); + let mut path: Vec = vec![start]; + let mut cur = start; + loop { + let next = tasks[cur] + .deps + .iter() + .map(|d| index[d]) + .find(|i| indegree[*i] > 0) + .unwrap_or(start); + if let Some(pos) = path.iter().position(|p| *p == next) { + let mut cycle: Vec = path[pos..].iter().map(|i| tasks[*i].id.clone()).collect(); + cycle.reverse(); + return cycle; + } + path.push(next); + cur = next; + } +} + +#[derive(Debug, Clone)] +pub struct WorkflowConfig { + pub run_id: RunId, + pub session_id: SessionId, + /// Upper bound on tasks running at once. Must be at least 1. + pub max_parallel: usize, + pub per_task_timeout: Option, + /// Wall-clock cap for the whole workflow. When it elapses the workflow is + /// cancelled like an operator cancel and `budget_exhausted` is set. + pub total_budget: Option, +} + +impl WorkflowConfig { + pub fn new(run_id: RunId, session_id: SessionId, max_parallel: usize) -> Self { + Self { + run_id, + session_id, + max_parallel, + per_task_timeout: None, + total_budget: None, + } + } +} + +/// Digest of a completed task's result. The value itself is not kept here. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ResultHandle { + pub digest: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum WorkflowStatus { + /// Every task completed. + Completed, + /// Some task failed, was skipped or cancelled, and nothing waits on a human. + Failed, + /// Cancelled (operator or budget). + Cancelled, + /// At least one task waits for approval; the workflow is not finished. + WaitingForApproval, +} + +/// One transition, in workflow order. `seq` starts at 1. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct WorkflowEvent { + pub seq: u64, + pub task_id: Option, + pub state: String, +} + +/// Serializable view of the in-memory workflow state. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct WorkflowSnapshot { + pub run_id: String, + pub last_seq: u64, + pub states: BTreeMap, + pub results: BTreeMap, +} + +#[derive(Debug, Clone)] +pub struct WorkflowReport { + pub status: WorkflowStatus, + pub snapshot: WorkflowSnapshot, + /// Failure records for Failed, Skipped and Cancelled tasks. + pub failures: BTreeMap, + /// Tasks left non-terminal (waiting for approval, or blocked behind one). + pub unfinished: Vec, + pub events: Vec, + pub peak_concurrency: usize, + pub budget_exhausted: bool, +} + +struct Ledger { + seq: u64, + states: BTreeMap, + results: BTreeMap, + failures: BTreeMap, + events: Vec, +} + +/// The one place a state change is recorded. The sequence number is assigned +/// under the lock together with the state change, so replay order equals +/// transition order. +struct Recorder { + ledger: Mutex, + bus: Option, + run_id: RunId, + session_id: SessionId, +} + +impl Recorder { + fn transition(&self, id: &TaskId, state: TaskState, result: Option) -> u64 { + let mut l = self.ledger.lock(); + l.seq += 1; + let seq = l.seq; + let name = state.name(); + let event = self.event_for(seq, id, &state, result.as_ref()); + if let Some(r) = result { + l.results.insert(id.clone(), r); + } + l.states.insert(id.clone(), state); + l.events.push(WorkflowEvent { + seq, + task_id: Some(id.clone()), + state: name.to_string(), + }); + // Publish while holding the lock so bus order equals sequence order. + self.publish(event, seq); + seq + } + + fn finish(&self, status: WorkflowStatus) { + let mut l = self.ledger.lock(); + l.seq += 1; + let seq = l.seq; + l.events.push(WorkflowEvent { + seq, + task_id: None, + state: "finished".to_string(), + }); + let event = AegisEvent::WorkflowFinished { + run_id: self.run_id.to_string(), + workflow_seq: seq, + status: format!("{status:?}").to_lowercase(), + }; + self.publish(event, seq); + } + + fn note_failure(&self, id: &TaskId, rec: FailureRecord) { + self.ledger.lock().failures.insert(id.clone(), rec); + } + + fn state_of(&self, id: &TaskId) -> TaskState { + self.ledger.lock().states[id].clone() + } + + fn next_failure_seq(&self) -> u64 { + // Failure records share the workflow sequence space; the number is + // only a stable order key, so the next transition's number is used. + self.ledger.lock().seq + 1 + } + + fn publish(&self, event: AegisEvent, seq: u64) { + if let Some(bus) = &self.bus { + let env = EventEnvelope::new( + event, + Some(self.session_id.to_string()), + Some(self.run_id.to_string()), + seq, + ); + // No subscriber is not an error for the workflow. + let _ = bus.publish(env); + } + } + + fn event_for( + &self, + seq: u64, + id: &TaskId, + state: &TaskState, + result: Option<&ResultHandle>, + ) -> AegisEvent { + let run_id = self.run_id.to_string(); + let task_id = id.to_string(); + match state { + TaskState::Pending => AegisEvent::WorkflowTaskReady { + run_id, + workflow_seq: seq, + task_id, + }, + TaskState::Ready => AegisEvent::WorkflowTaskReady { + run_id, + workflow_seq: seq, + task_id, + }, + TaskState::Running => AegisEvent::WorkflowTaskStarted { + run_id, + workflow_seq: seq, + task_id, + }, + TaskState::Completed => AegisEvent::WorkflowTaskCompleted { + run_id, + workflow_seq: seq, + task_id, + result_digest: result.map(|r| r.digest.clone()).unwrap_or_default(), + }, + TaskState::WaitingForApproval => AegisEvent::WorkflowTaskWaiting { + run_id, + workflow_seq: seq, + task_id, + }, + TaskState::Failed(rec) => AegisEvent::WorkflowTaskFailed { + run_id, + workflow_seq: seq, + task_id, + failure: rec.clone(), + }, + TaskState::Cancelled => AegisEvent::WorkflowTaskCancelled { + run_id, + workflow_seq: seq, + task_id, + }, + TaskState::Skipped { prerequisite } => AegisEvent::WorkflowTaskSkipped { + run_id, + workflow_seq: seq, + task_id, + prerequisite: prerequisite.to_string(), + }, + } + } +} + +enum Finish { + Outcome(TaskOutcome), + TimedOut, + Interrupted, +} + +pub struct WorkflowExecutor { + config: WorkflowConfig, + bus: Option, + cancel: CancelToken, +} + +impl WorkflowExecutor { + pub fn new(config: WorkflowConfig) -> Result { + if config.max_parallel == 0 { + return Err(WorkflowError::InvalidConfig( + "max_parallel must be at least 1".into(), + )); + } + Ok(Self { + config, + bus: None, + cancel: CancelToken::new(), + }) + } + + pub fn with_event_bus(mut self, bus: EventBus) -> Self { + self.bus = Some(bus); + self + } + + pub fn with_cancel_token(mut self, cancel: CancelToken) -> Self { + self.cancel = cancel; + self + } + + fn failure( + &self, + rec: &Recorder, + id: &TaskId, + class: FailureClass, + certainty: EffectCertainty, + message: &str, + ) -> FailureRecord { + let now = now_millis(); + FailureRecord::new( + rec.next_failure_seq(), + self.config.run_id.to_string(), + 0, + id.to_string(), + None, + WORKFLOW_TOOL_NAME, + 1, + class, + certainty, + now, + now, + ) + .with_cause("workflow", message, None) + } + + /// Runs the DAG to quiescence. Never blocks a worker thread: the + /// coordinator awaits, and task bodies run on spawned tasks. + pub async fn run(&self, spec: WorkflowSpec) -> WorkflowReport { + let ids = spec.task_ids(); + let rec = Recorder { + ledger: Mutex::new(Ledger { + seq: 0, + states: ids + .iter() + .map(|i| (i.clone(), TaskState::Pending)) + .collect(), + results: BTreeMap::new(), + failures: BTreeMap::new(), + events: Vec::new(), + }), + bus: self.bus.clone(), + run_id: self.config.run_id.clone(), + session_id: self.config.session_id.clone(), + }; + let nodes: HashMap = + spec.tasks.iter().map(|t| (t.id.clone(), t)).collect(); + let permits = Arc::new(Semaphore::new(self.config.max_parallel)); + let mut running: JoinSet<(TaskId, Finish)> = JoinSet::new(); + let mut by_join_id: HashMap = HashMap::new(); + let mut live = 0usize; + let mut peak = 0usize; + let mut cancel_seen = false; + let mut budget_exhausted = false; + let deadline = self + .config + .total_budget + .map(|d| tokio::time::Instant::now() + d); + + loop { + if !cancel_seen && self.cancel.is_cancelled() { + cancel_seen = true; + for id in &ids { + if matches!(rec.state_of(id), TaskState::Pending | TaskState::Ready) { + let f = self.failure( + &rec, + id, + FailureClass::Cancelled, + EffectCertainty::NoEffect, + "workflow cancelled before start", + ); + rec.note_failure(id, f); + rec.transition(id, TaskState::Cancelled, None); + } + } + } + + if !cancel_seen { + self.propagate(&ids, &nodes, &rec); + // Start ready tasks in insertion order while permits last. + for id in &ids { + if rec.state_of(id) != TaskState::Ready { + continue; + } + let Ok(permit) = permits.clone().try_acquire_owned() else { + break; + }; + rec.transition(id, TaskState::Running, None); + live += 1; + peak = peak.max(self.config.max_parallel - permits.available_permits()); + let node = nodes[id]; + let runner = node.runner.clone(); + let ctx = TaskContext { + task_id: id.clone(), + run_id: self.config.run_id.clone(), + session_id: self.config.session_id.clone(), + cancel: self.cancel.clone(), + }; + let cancel = self.cancel.clone(); + let timeout = self.config.per_task_timeout; + let tid = id.clone(); + let handle = running.spawn(async move { + let _permit = permit; + let body = runner.run(ctx); + let finish = tokio::select! { + biased; + _ = cancel.cancelled() => Finish::Interrupted, + f = async { + match timeout { + Some(d) => match tokio::time::timeout(d, body).await { + Ok(o) => Finish::Outcome(o), + Err(_) => Finish::TimedOut, + }, + None => Finish::Outcome(body.await), + } + } => f, + }; + (tid, finish) + }); + by_join_id.insert(handle.id(), id.clone()); + } + } + + if live == 0 { + break; + } + + let joined = tokio::select! { + j = running.join_next_with_id() => j, + _ = async { + match deadline { + Some(d) => tokio::time::sleep_until(d).await, + None => std::future::pending().await, + } + }, if !budget_exhausted => { + budget_exhausted = true; + self.cancel.cancel(); + continue; + } + }; + let Some(joined) = joined else { break }; + live -= 1; + let (jid, result) = match joined { + Ok((jid, r)) => (jid, Ok(r)), + Err(e) => (e.id(), Err(e)), + }; + let tid = by_join_id.remove(&jid).expect("tracked join id"); + let runner = nodes[&tid].runner.clone(); + let interrupt = runner.certainty_on_interrupt(); + let finish = match result { + Ok((_, f)) => f, + Err(_) => { + // A panicking body: the effect may have happened. + let f = self.failure( + &rec, + &tid, + FailureClass::Failed, + EffectCertainty::Uncertain, + "task body panicked", + ); + rec.note_failure(&tid, f.clone()); + rec.transition(&tid, TaskState::Failed(f), None); + continue; + } + }; + self.settle(&rec, &tid, finish, interrupt); + } + + self.report(rec, ids, peak, budget_exhausted, cancel_seen) + } + + /// Unblocks dependents whose prerequisites all completed, and skips + /// dependents of any prerequisite that ended without success. A task that + /// waits for approval is not terminal, so its dependents stay Pending. + fn propagate(&self, ids: &[TaskId], nodes: &HashMap, rec: &Recorder) { + loop { + let mut changed = false; + for id in ids { + if rec.state_of(id) != TaskState::Pending { + continue; + } + let deps = &nodes[id].deps; + let bad = deps.iter().find(|d| { + matches!( + rec.state_of(d), + TaskState::Failed(_) | TaskState::Cancelled | TaskState::Skipped { .. } + ) + }); + if let Some(bad) = bad { + let f = self.failure( + rec, + id, + FailureClass::Rejected, + EffectCertainty::NoEffect, + &format!("prerequisite failed: {bad}"), + ); + rec.note_failure(id, f); + rec.transition( + id, + TaskState::Skipped { + prerequisite: bad.clone(), + }, + None, + ); + changed = true; + } else if deps.iter().all(|d| rec.state_of(d) == TaskState::Completed) { + rec.transition(id, TaskState::Ready, None); + changed = true; + } + } + if !changed { + break; + } + } + } + + fn settle(&self, rec: &Recorder, id: &TaskId, finish: Finish, interrupt: EffectCertainty) { + match finish { + Finish::Outcome(TaskOutcome::Completed(v)) => { + let handle = ResultHandle { + digest: payload_digest(&v), + }; + rec.transition(id, TaskState::Completed, Some(handle)); + } + Finish::Outcome(TaskOutcome::Failed(fault)) => { + let f = self.failure(rec, id, fault.class, fault.certainty, &fault.message); + rec.note_failure(id, f.clone()); + rec.transition(id, TaskState::Failed(f), None); + } + Finish::Outcome(TaskOutcome::ApprovalPending) => { + rec.transition(id, TaskState::WaitingForApproval, None); + } + Finish::Outcome(TaskOutcome::Cancelled) | Finish::Interrupted => { + let f = self.failure( + rec, + id, + FailureClass::Cancelled, + interrupt, + "task cancelled while running", + ); + rec.note_failure(id, f); + rec.transition(id, TaskState::Cancelled, None); + } + Finish::TimedOut => { + let f = self.failure( + rec, + id, + FailureClass::Timeout, + interrupt, + "per-task timeout elapsed", + ); + rec.note_failure(id, f.clone()); + rec.transition(id, TaskState::Failed(f), None); + } + } + } + + fn report( + &self, + rec: Recorder, + ids: Vec, + peak: usize, + budget_exhausted: bool, + cancelled: bool, + ) -> WorkflowReport { + let (unfinished, any_waiting, all_done) = { + let l = rec.ledger.lock(); + let unfinished: Vec = ids + .iter() + .filter(|i| !l.states[*i].is_terminal()) + .cloned() + .collect(); + let any_waiting = l + .states + .values() + .any(|s| matches!(s, TaskState::WaitingForApproval)); + let all_done = l.states.values().all(|s| matches!(s, TaskState::Completed)); + (unfinished, any_waiting, all_done) + }; + let status = if cancelled { + WorkflowStatus::Cancelled + } else if any_waiting { + WorkflowStatus::WaitingForApproval + } else if all_done { + WorkflowStatus::Completed + } else { + WorkflowStatus::Failed + }; + rec.finish(status); + let l = rec.ledger.lock(); + WorkflowReport { + status, + snapshot: WorkflowSnapshot { + run_id: self.config.run_id.to_string(), + last_seq: l.seq, + states: l.states.clone(), + results: l.results.clone(), + }, + failures: l.failures.clone(), + unfinished, + events: l.events.clone(), + peak_concurrency: peak, + budget_exhausted, + } + } +} + +/// Maps a finished `AgentEngine::execute_task` result onto a task outcome. +/// This is the whole adapter seam: the agent already gates every tool call, +/// so the DAG adds no authority here. +pub fn agent_outcome(result: &crate::agent::AgentExecutionResult) -> TaskOutcome { + let last_failure = result + .steps + .iter() + .flat_map(|s| s.tool_calls.iter()) + .filter_map(|c| c.failure.as_ref()) + .next_back(); + if let Some(f) = last_failure { + if f.class == FailureClass::ApprovalPending { + return TaskOutcome::ApprovalPending; + } + let msg = f + .cause + .first() + .map(|c| c.message.clone()) + .unwrap_or_else(|| "agent tool call failed".into()); + return TaskOutcome::Failed(ToolFault::new(f.class, f.effect_certainty, msg)); + } + if result.completed { + TaskOutcome::Completed(serde_json::json!({ "final_response": result.final_response })) + } else { + // Ran out of turns: tools may have acted, so claim no certainty. + TaskOutcome::Failed(ToolFault::new( + FailureClass::Failed, + EffectCertainty::Uncertain, + "agent did not complete within its turn budget", + )) + } +} + +/// Runs one `AgentEngine::execute_task` call as a workflow task. +pub struct AgentTaskRunner { + pub engine: Arc, + pub goal: String, + pub max_turns: usize, +} + +#[async_trait] +impl TaskRunner for AgentTaskRunner { + async fn run(&self, _ctx: TaskContext) -> TaskOutcome { + match self + .engine + .execute_task(&self.goal, None, self.max_turns) + .await + { + Ok(r) => agent_outcome(&r), + Err(e) => TaskOutcome::Failed(ToolFault::new( + FailureClass::Failed, + EffectCertainty::Uncertain, + e.to_string(), + )), + } + } +} 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..dd48b57 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:05:01Z", "compiler": "crumb-compile/1", - "digest": "sha256:f4bd4396bc580ae13307cfae0811c25db094a9c1b1a5ec06c094f19e20ae6382", + "digest": "sha256:df847e5d91ae7ee6ec75ad9abc538714dc43f89449684f8827b09a6108ea0d2e", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 9, - "generated_at_commit": "7288fa65b22fe45e36a88f44150f21ed8781dc89", - "source_tree": "sha256:eef5040b25d3c7f1141d6420234488b1411af9a947fcfb695c7478f64a91ead3" + "files": 11, + "generated_at_commit": "e21dab3edbdededb2396a74d0614c797b912bb6a", + "source_tree": "sha256:5da247af43d882b241d26788cf1e16fe963f108ba4c49efd8d7fec82220cf485" }, "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