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#41 (code only)
closed derived 45605ef1ce5c3e8d #41
Imported from GitHub aien-dev/aegis-runtime-mv#41 (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 4a85ddc702bb41e8fd21e41ed6d851ea38ac1a54
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 #41 ("feat: dependency-aware task workflow DAG (#39)") 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 #41 ("feat: dependency-aware task workflow DAG (#39)") 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:05 UTC
⚖️ Sovereign Code Review & Alignment Gate
Greetings @aien-dev. I am AIEN , resident sovereign intelligence of SparkOS.
Your pull request #41 ("feat: dependency-aware task workflow DAG (#39)") 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 #41 ("feat: dependency-aware task workflow DAG (#39)") 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-45605ef1ce5c3e8d f4e870953a466bb1cf68f1d88285929024cf1ba9
curl -fsSL https://interplane.io/drakestapleton/aegis-runtime-mv/patches/45605ef1ce5c3e8d .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
41
4a85ddc702bb41e8fd21e41ed6d851ea38ac1a54
{"kind":"github-import","owner":"aien-dev","repo":"aegis-runtime-mv","number":41,"url":"https://github.com/aien-dev/aegis-runtime-mv/pull/41","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452 ","imported_utc":"2026-11-18T16:39:36Z","metadata":"unavailable","state_derived":true}
Changes
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: <id>`. 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<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 ..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<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 ..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<String>) -> 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<TaskId>),
+ 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: F,
+ interrupt: EffectCertainty,
+}
+
+pub fn runner_fn<F>(f: F) -> Arc<dyn TaskRunner>
+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: F, interrupt: EffectCertainty) -> Arc<dyn TaskRunner>
+where
+ F: Fn(TaskContext) -> BoxFuture<'static, TaskOutcome> + Send + Sync + 'static,
+{
+ Arc::new(FnRunner { f, interrupt })
+}
+
+#[async_trait]
+impl<F> TaskRunner for FnRunner<F>
+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<TaskId>,
+ runner: Arc<dyn TaskRunner>,
+}
+
+/// A validated DAG. Insertion order is the deterministic tie break.
+pub struct WorkflowSpec {
+ tasks: Vec<TaskNode>,
+}
+
+impl WorkflowSpec {
+ pub fn builder() -> WorkflowBuilder {
+ WorkflowBuilder::default()
+ }
+
+ pub fn task_ids(&self) -> Vec<TaskId> {
+ 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<TaskNode>,
+}
+
+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<TaskId>,
+ deps: &[&str],
+ runner: Arc<dyn TaskRunner>,
+ ) -> Result<Self, WorkflowError> {
+ 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<WorkflowSpec, WorkflowError> {
+ 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<usize> = self.tasks.iter().map(|t| t.deps.len()).collect();
+ let mut queue: Vec<usize> = (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<TaskId> {
+ let start = (0..tasks.len()).find(|i| indegree[*i] > 0).unwrap_or(0);
+ let mut path: Vec<usize> = 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<TaskId> = 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<Duration>,
+ /// 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<Duration>,
+}
+
+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<TaskId>,
+ 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<TaskId, TaskState>,
+ pub results: BTreeMap<TaskId, ResultHandle>,
+}
+
+#[derive(Debug, Clone)]
+pub struct WorkflowReport {
+ pub status: WorkflowStatus,
+ pub snapshot: WorkflowSnapshot,
+ /// Failure records for Failed, Skipped and Cancelled tasks.
+ pub failures: BTreeMap<TaskId, FailureRecord>,
+ /// Tasks left non-terminal (waiting for approval, or blocked behind one).
+ pub unfinished: Vec<TaskId>,
+ pub events: Vec<WorkflowEvent>,
+ pub peak_concurrency: usize,
+ pub budget_exhausted: bool,
+}
+
+struct Ledger {
+ seq: u64,
+ states: BTreeMap<TaskId, TaskState>,
+ results: BTreeMap<TaskId, ResultHandle>,
+ failures: BTreeMap<TaskId, FailureRecord>,
+ events: Vec<WorkflowEvent>,
+}
+
+/// 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<Ledger>,
+ bus: Option<EventBus>,
+ run_id: RunId,
+ session_id: SessionId,
+}
+
+impl Recorder {
+ fn transition(&self, id: &TaskId, state: TaskState, result: Option<ResultHandle>) -> 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<EventBus>,
+ cancel: CancelToken,
+}
+
+impl WorkflowExecutor {
+ pub fn new(config: WorkflowConfig) -> Result<Self, WorkflowError> {
+ 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<TaskId, &TaskNode> =
+ 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<tokio::task::Id, TaskId> = 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<TaskId, &TaskNode>, 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<TaskId>,
+ peak: usize,
+ budget_exhausted: bool,
+ cancelled: bool,
+ ) -> WorkflowReport {
+ let (unfinished, any_waiting, all_done) = {
+ let l = rec.ledger.lock();
+ let unfinished: Vec<TaskId> = 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<crate::agent::AgentEngine>,
+ 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<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 ..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<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);
+}
diff --git a/tests/workflow_dag_tests.rs b/tests/workflow_dag_tests.rs
new file mode 100644
index 0000000 ..6f23f69
--- /dev/null
+++ b/tests/workflow_dag_tests.rs
@@ -0,0 +1,596 @@
+//! Task DAG tests (issue #39). CPU only, deterministic ordering assertions,
+//! sleep-based fake tasks. Timings are printed for information, never asserted.
+
+use aegis::orchestration::workflow::{
+ runner_fn, runner_fn_with_certainty, TaskContext, TaskOutcome, WorkflowBuilder,
+};
+use aegis::{
+ AegisEvent, CancelToken, EffectCertainty, EventBus, FailureClass, RunId, SessionId, TaskId,
+ TaskRunner, TaskState, ToolFault, WorkflowConfig, WorkflowError, WorkflowExecutor,
+ WorkflowSpec, WorkflowStatus,
+};
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+fn cfg(max_parallel: usize) -> WorkflowConfig {
+ WorkflowConfig::new(
+ RunId::from_string("run_test"),
+ SessionId::from_string("sess_test"),
+ max_parallel,
+ )
+}
+
+fn ok(ms: u64) -> Arc<dyn TaskRunner> {
+ runner_fn(move |_c: TaskContext| {
+ Box::pin(async move {
+ tokio::time::sleep(Duration::from_millis(ms)).await;
+ TaskOutcome::Completed(serde_json::json!({ "ms": ms }))
+ })
+ })
+}
+
+fn failing(class: FailureClass, cert: EffectCertainty) -> Arc<dyn TaskRunner> {
+ runner_fn(move |_c: TaskContext| {
+ Box::pin(async move { TaskOutcome::Failed(ToolFault::new(class, cert, "boom")) })
+ })
+}
+
+fn tid(s: &str) -> TaskId {
+ TaskId::new(s)
+}
+
+fn b() -> WorkflowBuilder {
+ WorkflowSpec::builder()
+}
+
+/// Records start/finish order and a counter of runs per task.
+struct Probe {
+ log: Mutex<Vec<String>>,
+ runs: Mutex<std::collections::HashMap<String, usize>>,
+ live: AtomicUsize,
+ peak: AtomicUsize,
+}
+
+impl Probe {
+ fn new() -> Arc<Self> {
+ Arc::new(Self {
+ log: Mutex::new(vec![]),
+ runs: Mutex::new(Default::default()),
+ live: AtomicUsize::new(0),
+ peak: AtomicUsize::new(0),
+ })
+ }
+
+ fn task(self: &Arc<Self>, name: &'static str, ms: u64) -> Arc<dyn TaskRunner> {
+ let p = self.clone();
+ runner_fn(move |_c| {
+ let p = p.clone();
+ Box::pin(async move {
+ let now = p.live.fetch_add(1, Ordering::SeqCst) + 1;
+ p.peak.fetch_max(now, Ordering::SeqCst);
+ p.log.lock().unwrap().push(format!("start:{name}"));
+ *p.runs.lock().unwrap().entry(name.into()).or_default() += 1;
+ tokio::time::sleep(Duration::from_millis(ms)).await;
+ p.log.lock().unwrap().push(format!("end:{name}"));
+ p.live.fetch_sub(1, Ordering::SeqCst);
+ TaskOutcome::Completed(serde_json::json!(name))
+ })
+ })
+ }
+
+ fn runs(&self, name: &str) -> usize {
+ self.runs.lock().unwrap().get(name).copied().unwrap_or(0)
+ }
+
+ fn pos(&self, entry: &str) -> usize {
+ self.log
+ .lock()
+ .unwrap()
+ .iter()
+ .position(|e| e == entry)
+ .unwrap_or_else(|| panic!("missing {entry}"))
+ }
+}
+
+#[tokio::test]
+async fn fixture_a_b_independent_c_waits_d_blocked_on_failure() {
+ let p = Probe::new();
+ let spec = b()
+ .add_task("A", &[], p.task("A", 30))
+ .unwrap()
+ .add_task("B", &[], p.task("B", 30))
+ .unwrap()
+ .add_task("C", &["A", "B"], p.task("C", 5))
+ .unwrap()
+ .add_task(
+ "F",
+ &[],
+ failing(FailureClass::Failed, EffectCertainty::EffectOccurred),
+ )
+ .unwrap()
+ .add_task("D", &["F"], p.task("D", 5))
+ .unwrap()
+ .build()
+ .unwrap();
+ let r = WorkflowExecutor::new(cfg(4)).unwrap().run(spec).await;
+
+ assert_eq!(p.runs("C"), 1, "C runs exactly once");
+ assert!(p.pos("end:A") < p.pos("start:C"));
+ assert!(p.pos("end:B") < p.pos("start:C"));
+ assert!(p.pos("start:B") < p.pos("end:A"), "A and B overlapped");
+ assert_eq!(p.runs("D"), 0, "D never starts");
+ assert_eq!(r.snapshot.states[&tid("C")], TaskState::Completed);
+ assert!(matches!(r.snapshot.states[&tid("F")], TaskState::Failed(_)));
+ assert_eq!(
+ r.snapshot.states[&tid("D")],
+ TaskState::Skipped {
+ prerequisite: tid("F")
+ }
+ );
+ let rec = &r.failures[&tid("D")];
+ assert_eq!(rec.class, FailureClass::Rejected);
+ assert_eq!(rec.effect_certainty, EffectCertainty::NoEffect);
+ assert_eq!(rec.cause[0].message, "prerequisite failed: F");
+ assert_eq!(r.status, WorkflowStatus::Failed);
+ assert!(r.snapshot.results.contains_key(&tid("C")));
+ assert!(!r.snapshot.results.contains_key(&tid("D")));
+}
+
+#[tokio::test]
+async fn skip_propagates_transitively() {
+ let spec = b()
+ .add_task(
+ "F",
+ &[],
+ failing(FailureClass::Rejected, EffectCertainty::NoEffect),
+ )
+ .unwrap()
+ .add_task("X", &["F"], ok(1))
+ .unwrap()
+ .add_task("Y", &["X"], ok(1))
+ .unwrap()
+ .build()
+ .unwrap();
+ let r = WorkflowExecutor::new(cfg(2)).unwrap().run(spec).await;
+ assert_eq!(
+ r.snapshot.states[&tid("X")],
+ TaskState::Skipped {
+ prerequisite: tid("F")
+ }
+ );
+ assert_eq!(
+ r.snapshot.states[&tid("Y")],
+ TaskState::Skipped {
+ prerequisite: tid("X")
+ }
+ );
+}
+
+#[test]
+fn rejects_cycle() {
+ let spec = b()
+ .add_task("A", &["C"], ok(1))
+ .unwrap()
+ .add_task("B", &["A"], ok(1))
+ .unwrap()
+ .add_task("C", &["B"], ok(1))
+ .unwrap()
+ .add_task("Z", &[], ok(1))
+ .unwrap()
+ .build();
+ match spec {
+ Err(WorkflowError::Cycle(c)) => {
+ assert_eq!(c.len(), 3);
+ assert!(!c.contains(&tid("Z")));
+ }
+ _ => panic!("expected cycle"),
+ }
+}
+
+#[test]
+fn rejects_self_dependency() {
+ let e = b().add_task("A", &["A"], ok(1)).err().unwrap();
+ assert_eq!(e, WorkflowError::SelfDependency(tid("A")));
+}
+
+#[test]
+fn rejects_unknown_predecessor() {
+ let e = b()
+ .add_task("A", &["ghost"], ok(1))
+ .unwrap()
+ .build()
+ .err()
+ .unwrap();
+ assert_eq!(
+ e,
+ WorkflowError::UnknownPredecessor {
+ task: tid("A"),
+ predecessor: tid("ghost")
+ }
+ );
+}
+
+#[test]
+fn rejects_duplicate_task_and_duplicate_edge() {
+ let e = b()
+ .add_task("A", &[], ok(1))
+ .unwrap()
+ .add_task("A", &[], ok(1))
+ .err()
+ .unwrap();
+ assert_eq!(e, WorkflowError::DuplicateTask(tid("A")));
+ let e = b()
+ .add_task("A", &[], ok(1))
+ .unwrap()
+ .add_task("B", &["A", "A"], ok(1))
+ .err()
+ .unwrap();
+ assert_eq!(
+ e,
+ WorkflowError::DuplicateEdge {
+ task: tid("B"),
+ predecessor: tid("A")
+ }
+ );
+}
+
+#[test]
+fn rejects_zero_parallelism() {
+ assert!(matches!(
+ WorkflowExecutor::new(cfg(0)),
+ Err(WorkflowError::InvalidConfig(_))
+ ));
+}
+
+#[tokio::test]
+async fn timeout_is_failed_timeout_with_runner_certainty() {
+ let slow = |c: EffectCertainty| {
+ runner_fn_with_certainty(
+ |_c| {
+ Box::pin(async {
+ tokio::time::sleep(Duration::from_secs(30)).await;
+ TaskOutcome::Completed(serde_json::json!(null))
+ })
+ },
+ c,
+ )
+ };
+ let spec = b()
+ .add_task("read_only", &[], slow(EffectCertainty::NoEffect))
+ .unwrap()
+ .add_task("writer", &[], slow(EffectCertainty::Uncertain))
+ .unwrap()
+ .add_task("after", &["writer"], ok(1))
+ .unwrap()
+ .build()
+ .unwrap();
+ let mut c = cfg(2);
+ c.per_task_timeout = Some(Duration::from_millis(40));
+ let r = WorkflowExecutor::new(c).unwrap().run(spec).await;
+ for (id, cert) in [
+ ("read_only", EffectCertainty::NoEffect),
+ ("writer", EffectCertainty::Uncertain),
+ ] {
+ match &r.snapshot.states[&tid(id)] {
+ TaskState::Failed(f) => {
+ assert_eq!(f.class, FailureClass::Timeout);
+ assert_eq!(f.effect_certainty, cert);
+ }
+ other => panic!("{id}: {other:?}"),
+ }
+ }
+ assert!(matches!(
+ r.snapshot.states[&tid("after")],
+ TaskState::Skipped { .. }
+ ));
+}
+
+#[tokio::test]
+async fn cancellation_cancels_running_and_pending_and_starts_nothing_new() {
+ let p = Probe::new();
+ let spec = b()
+ .add_task(
+ "long",
+ &[],
+ runner_fn(|c: TaskContext| {
+ Box::pin(async move {
+ c.cancel.cancelled().await;
+ TaskOutcome::Cancelled
+ })
+ }),
+ )
+ .unwrap()
+ .add_task("next", &["long"], p.task("next", 1))
+ .unwrap()
+ .add_task("other", &[], p.task("other", 1))
+ .unwrap()
+ .build()
+ .unwrap();
+ let cancel = CancelToken::new();
+ let c2 = cancel.clone();
+ let exec = WorkflowExecutor::new(cfg(1))
+ .unwrap()
+ .with_cancel_token(cancel);
+ let h = tokio::spawn(async move { exec.run(spec).await });
+ tokio::time::sleep(Duration::from_millis(30)).await;
+ c2.cancel();
+ let r = h.await.unwrap();
+ assert_eq!(r.status, WorkflowStatus::Cancelled);
+ assert_eq!(r.snapshot.states[&tid("long")], TaskState::Cancelled);
+ assert_eq!(r.snapshot.states[&tid("next")], TaskState::Cancelled);
+ assert_eq!(r.snapshot.states[&tid("other")], TaskState::Cancelled);
+ assert_eq!(p.runs("next") + p.runs("other"), 0);
+}
+
+#[tokio::test]
+async fn total_budget_cancels_the_workflow() {
+ let spec = b()
+ .add_task("slow", &[], ok(10_000))
+ .unwrap()
+ .add_task("n", &["slow"], ok(1))
+ .unwrap()
+ .build()
+ .unwrap();
+ let mut c = cfg(2);
+ c.total_budget = Some(Duration::from_millis(40));
+ let r = WorkflowExecutor::new(c).unwrap().run(spec).await;
+ assert!(r.budget_exhausted);
+ assert_eq!(r.status, WorkflowStatus::Cancelled);
+ assert_eq!(r.snapshot.states[&tid("slow")], TaskState::Cancelled);
+ assert_eq!(r.snapshot.states[&tid("n")], TaskState::Cancelled);
+}
+
+#[tokio::test]
+async fn max_parallel_is_honoured() {
+ for limit in [1usize, 2, 3] {
+ let p = Probe::new();
+ let mut bld = b();
+ for n in ["t1", "t2", "t3", "t4", "t5", "t6"] {
+ bld = bld.add_task(n, &[], p.task(n, 15)).unwrap();
+ }
+ let r = WorkflowExecutor::new(cfg(limit))
+ .unwrap()
+ .run(bld.build().unwrap())
+ .await;
+ assert_eq!(r.status, WorkflowStatus::Completed);
+ assert!(p.peak.load(Ordering::SeqCst) <= limit, "limit {limit}");
+ assert_eq!(
+ p.peak.load(Ordering::SeqCst),
+ limit,
+ "limit {limit} is reached"
+ );
+ assert!(r.peak_concurrency <= limit);
+ }
+}
+
+#[tokio::test]
+async fn approval_pending_blocks_dependents_and_is_not_success() {
+ let p = Probe::new();
+ let spec = b()
+ .add_task(
+ "gate",
+ &[],
+ runner_fn(|_c| Box::pin(async { TaskOutcome::ApprovalPending })),
+ )
+ .unwrap()
+ .add_task("after", &["gate"], p.task("after", 1))
+ .unwrap()
+ .add_task("later", &["after"], p.task("later", 1))
+ .unwrap()
+ .add_task("free", &[], p.task("free", 1))
+ .unwrap()
+ .build()
+ .unwrap();
+ let r = WorkflowExecutor::new(cfg(2)).unwrap().run(spec).await;
+ assert_eq!(r.status, WorkflowStatus::WaitingForApproval);
+ assert_eq!(
+ r.snapshot.states[&tid("gate")],
+ TaskState::WaitingForApproval
+ );
+ assert_eq!(r.snapshot.states[&tid("after")], TaskState::Pending);
+ assert_eq!(r.snapshot.states[&tid("free")], TaskState::Completed);
+ assert_eq!(p.runs("after") + p.runs("later"), 0);
+ assert_eq!(r.unfinished, vec![tid("gate"), tid("after"), tid("later")]);
+}
+
+#[tokio::test]
+async fn uncertain_outcome_is_never_rescheduled() {
+ let n = Arc::new(AtomicUsize::new(0));
+ let n2 = n.clone();
+ let spec = b()
+ .add_task(
+ "write",
+ &[],
+ runner_fn(move |_c| {
+ let n = n2.clone();
+ Box::pin(async move {
+ n.fetch_add(1, Ordering::SeqCst);
+ TaskOutcome::Failed(ToolFault::new(
+ FailureClass::Uncertain,
+ EffectCertainty::Uncertain,
+ "lost response",
+ ))
+ })
+ }),
+ )
+ .unwrap()
+ .add_task("dep", &["write"], ok(1))
+ .unwrap()
+ .build()
+ .unwrap();
+ let r = WorkflowExecutor::new(cfg(2)).unwrap().run(spec).await;
+ assert_eq!(n.load(Ordering::SeqCst), 1);
+ match &r.snapshot.states[&tid("write")] {
+ TaskState::Failed(f) => {
+ assert_eq!(f.class, FailureClass::Uncertain);
+ assert_eq!(f.effect_certainty, EffectCertainty::Uncertain);
+ }
+ o => panic!("{o:?}"),
+ }
+ assert!(matches!(
+ r.snapshot.states[&tid("dep")],
+ TaskState::Skipped { .. }
+ ));
+}
+
+fn diamond(p: &Arc<Probe>) -> WorkflowSpec {
+ b().add_task("A", &[], p.task("A", 5))
+ .unwrap()
+ .add_task("B", &["A"], p.task("B", 5))
+ .unwrap()
+ .add_task("C", &["A"], p.task("C", 5))
+ .unwrap()
+ .add_task("D", &["B", "C"], p.task("D", 5))
+ .unwrap()
+ .build()
+ .unwrap()
+}
+
+#[tokio::test]
+async fn event_sequence_is_deterministic_and_matches_the_bus() {
+ let mut runs = vec![];
+ for _ in 0..2 {
+ let bus = EventBus::default();
+ let mut rx = bus.subscribe();
+ let p = Probe::new();
+ // max_parallel 1 removes completion races, so the whole order is fixed.
+ let r = WorkflowExecutor::new(cfg(1))
+ .unwrap()
+ .with_event_bus(bus)
+ .run(diamond(&p))
+ .await;
+ let mut bus_seq = vec![];
+ while let Ok(env) = rx.try_recv() {
+ let name = match env.event {
+ AegisEvent::WorkflowTaskReady { task_id, .. } => format!("ready:{task_id}"),
+ AegisEvent::WorkflowTaskStarted { task_id, .. } => format!("started:{task_id}"),
+ AegisEvent::WorkflowTaskCompleted {
+ task_id,
+ result_digest,
+ ..
+ } => {
+ assert!(result_digest.starts_with("sha256:"));
+ format!("completed:{task_id}")
+ }
+ AegisEvent::WorkflowFinished { .. } => "finished".into(),
+ other => panic!("unexpected {other:?}"),
+ };
+ bus_seq.push((env.sequence, name));
+ }
+ let from_report: Vec<(u64, String)> = r
+ .events
+ .iter()
+ .map(|e| {
+ let n = match &e.task_id {
+ Some(t) => format!("{}:{t}", e.state),
+ None => e.state.clone(),
+ };
+ (e.seq, n.replace("running", "started"))
+ })
+ .collect();
+ assert_eq!(bus_seq, from_report, "bus order equals recorded order");
+ let seqs: Vec<u64> = bus_seq.iter().map(|e| e.0).collect();
+ assert_eq!(seqs, (1..=seqs.len() as u64).collect::<Vec<_>>());
+ runs.push(bus_seq);
+ }
+ assert_eq!(runs[0], runs[1]);
+}
+
+#[tokio::test]
+async fn parallel_run_sequence_is_gapless_and_orders_dependencies() {
+ let p = Probe::new();
+ let r = WorkflowExecutor::new(cfg(4))
+ .unwrap()
+ .run(diamond(&p))
+ .await;
+ let seqs: Vec<u64> = r.events.iter().map(|e| e.seq).collect();
+ assert_eq!(seqs, (1..=seqs.len() as u64).collect::<Vec<_>>());
+ let at = |t: &str, s: &str| {
+ r.events
+ .iter()
+ .find(|e| e.task_id.as_ref().map(|x| x.as_str()) == Some(t) && e.state == s)
+ .unwrap()
+ .seq
+ };
+ assert!(at("A", "completed") < at("B", "ready"));
+ assert!(at("B", "completed") < at("D", "ready"));
+ assert!(at("C", "completed") < at("D", "ready"));
+}
+
+#[tokio::test]
+async fn snapshot_is_serializable_and_deterministic() {
+ let p = Probe::new();
+ let r = WorkflowExecutor::new(cfg(1))
+ .unwrap()
+ .run(diamond(&p))
+ .await;
+ let j1 = serde_json::to_string(&r.snapshot).unwrap();
+ let j2 = serde_json::to_string(&r.snapshot.clone()).unwrap();
+ assert_eq!(j1, j2);
+ let back: aegis::orchestration::workflow::WorkflowSnapshot = serde_json::from_str(&j1).unwrap();
+ assert_eq!(back, r.snapshot);
+ // A failed task also round trips (it carries a FailureRecord).
+ let spec = b()
+ .add_task(
+ "F",
+ &[],
+ failing(FailureClass::Failed, EffectCertainty::EffectOccurred),
+ )
+ .unwrap()
+ .build()
+ .unwrap();
+ let r = WorkflowExecutor::new(cfg(1)).unwrap().run(spec).await;
+ let j = serde_json::to_string(&r.snapshot).unwrap();
+ let back: aegis::orchestration::workflow::WorkflowSnapshot = serde_json::from_str(&j).unwrap();
+ assert_eq!(back, r.snapshot);
+}
+
+/// Demo: edit and lint are independent, test needs both, a build task fails
+/// and its dependent report is skipped. Same four-plus tasks run with
+/// max_parallel 1 (sequential) and 2. Only ordering and the bound are asserted.
+#[tokio::test]
+async fn demo_code_test_eval_dag_sequential_vs_parallel() {
+ async fn run(
+ limit: usize,
+ p: &Arc<Probe>,
+ ) -> (Duration, aegis::orchestration::workflow::WorkflowReport) {
+ let spec = b()
+ .add_task("edit", &[], p.task("edit", 40))
+ .unwrap()
+ .add_task("lint", &[], p.task("lint", 40))
+ .unwrap()
+ .add_task("test", &["edit", "lint"], p.task("test", 20))
+ .unwrap()
+ .add_task(
+ "build_docs",
+ &[],
+ failing(FailureClass::Failed, EffectCertainty::EffectOccurred),
+ )
+ .unwrap()
+ .add_task("report", &["build_docs"], p.task("report", 20))
+ .unwrap()
+ .build()
+ .unwrap();
+ let t = Instant::now();
+ let r = WorkflowExecutor::new(cfg(limit)).unwrap().run(spec).await;
+ (t.elapsed(), r)
+ }
+ let p1 = Probe::new();
+ let (seq_t, r1) = run(1, &p1).await;
+ let p2 = Probe::new();
+ let (par_t, r2) = run(2, &p2).await;
+ println!("INFO sequential(max_parallel=1) {seq_t:?} dag(max_parallel=2) {par_t:?}");
+ assert!(p1.peak.load(Ordering::SeqCst) <= 1);
+ assert!(p2.peak.load(Ordering::SeqCst) <= 2);
+ assert!(p2.pos("end:edit") < p2.pos("start:test"));
+ assert!(p2.pos("end:lint") < p2.pos("start:test"));
+ assert_eq!(p2.runs("report"), 0);
+ for r in [&r1, &r2] {
+ assert_eq!(r.snapshot.states[&tid("test")], TaskState::Completed);
+ assert!(matches!(
+ r.snapshot.states[&tid("report")],
+ TaskState::Skipped { .. }
+ ));
+ }
+}