Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .github/workflows/ares2-graph-custody.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
name: Ares2 P05 - graph terminal custody focused Rust qualification
on:
pull_request:
paths:
- 'agent-graph-mcp/**'
- '.github/workflows/ares2-graph-custody.yml'
permissions:
contents: read
jobs:
signed-bundle-warm-cold-receipt:
runs-on: ubuntu-latest
timeout-minutes: 35
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
- uses: Swatinem/rust-cache@v2
- name: Verify exact checkout and formatting
shell: bash
run: |
set -Eeuo pipefail
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
cargo fmt --all -- --check
- name: Compile and test the real Graph daemon cold/warm custody contract
shell: bash
run: |
set -Eeuo pipefail
cargo test -p agent-graph-mcp --test mcp_integration
cargo test -p agent-graph-mcp --lib
cargo clippy -p agent-graph-mcp --all-targets -- -D warnings
2 changes: 1 addition & 1 deletion agent-graph-mcp/src/run_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -701,7 +701,7 @@ impl RunManager {
.iter()
.filter_map(|m| m.get("model_alias").cloned())
.collect();
let receipt = serde_json::json!({"schema":"agent-graph-mcp-receipt-v1","run_id":run_id,"trace":trace,"graph_version":graph_version,
let receipt = serde_json::json!({"schema":"agent-graph-mcp-receipt-v2","run_id":run_id,"trace":trace,"graph_version":graph_version,
"input_digest":digest(&input),"output_digest":digest(&state_value),"step_count":steps.len(),"models":models,
"provider":provider,"default_model":configured_model,"model_labels":model_labels,
"core":core_receipt,"dependency_envelopes":dependency_envelopes,"dependency_envelopes_complete":dependency_envelopes_complete,"replay_capability":if resumed { "deterministic_local_resume" } else { "integrity_only" },
Expand Down
82 changes: 48 additions & 34 deletions agent-graph-mcp/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2291,28 +2291,37 @@ impl AgentGraphServer {
.ok_or_else(|| invalid_params(format!("run '{run_id}' not found")))?
};
if matches!(r.status.as_str(), "completed" | "failed" | "cancelled") {
let persist = Self::persist_terminal(self.store.clone(), r.clone());
if let Ok(runs) = self.runs.lock() {
if self.store.is_none() {
runs.mark_persistence(&run_id, "volatile_no_store", None);
} else {
match persist {
Ok(()) => runs.mark_persistence(&run_id, "durable_terminal", None),
Err(error) => runs.mark_persistence(
&run_id,
"volatile_persistence_failed",
Some(error),
),
}
// Completion is not durability. The single async completion
// callback owns terminal persistence and acknowledgement.
// Writing again from a waiter races with that owner and can
// replace a signed terminal record with a stale projection.
if self.store.is_some() && r.persistence_status == "pending" {
if Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
continue;
}
return Ok(output_with_meta(
serde_json::json!({
"run_id": run_id,
"status": "terminal_persistence_pending",
"timed_out": true,
"completion_unknown": true
}),
None,
None,
Some(&run_id),
));
}
let mut public = self
.runs
.lock()
.ok()
.and_then(|runs| runs.get(&run_id).map(|record| record.public()))
.unwrap_or_else(|| r.public());
if let Ok(Some(stored)) = self.stored_run(&run_id) {
let mut public = r.public();
if self.store.is_some() && r.persistence_status == "durable_terminal" {
// Never trust a cold or warm terminal claim if the
// persisted receipt cannot be independently reread.
let Some(stored) = self.stored_run(&run_id).ok().flatten() else {
return Ok(error_output(
"durable terminal record could not be verified",
"DURABLE_TERMINAL_UNVERIFIED",
));
};
if let (Some(public_object), Some(stored_object)) =
(public.as_object_mut(), stored.as_object())
{
Expand Down Expand Up @@ -2483,19 +2492,9 @@ impl AgentGraphServer {
&self,
Parameters(RunReceiptParams { run_id }): Parameters<RunReceiptParams>,
) -> Result<Json<StructuredOutput>, ErrorData> {
if let Some(r) = self
.runs
.lock()
.map_err(|e| internal_error(e.to_string()))?
.get(&run_id)
{
return Ok(output_with_meta(
r.receipt.clone(),
None,
None,
Some(&run_id),
));
}
// The durable SQLite record is the canonical terminal owner. Never
// return the in-memory pre-persistence copy ahead of a signed record,
// and never bypass a failed integrity check by falling back to cache.
if let Some(store) = &self.store {
match store.load_terminal_receipt(&run_id) {
Ok(Some(receipt)) => {
Expand All @@ -2504,7 +2503,7 @@ impl AgentGraphServer {
Ok(None) => {}
Err(error) if error == "RECEIPT_INTEGRITY_FAILURE" => {
return Ok(error_output(
"terminal receipt integrity validation failed",
"terminal receipt or bundle integrity validation failed",
"RECEIPT_INTEGRITY_FAILURE",
));
}
Expand All @@ -2517,6 +2516,21 @@ impl AgentGraphServer {
Err(error) => return Err(internal_error(error)),
}
}
if let Some(r) = self
.runs
.lock()
.map_err(|e| internal_error(e.to_string()))?
.get(&run_id)
{
// A volatile in-flight receipt has neither a durable bundle nor
// a signed terminal outcome; Ares will refuse it as incomplete.
return Ok(output_with_meta(
r.receipt.clone(),
None,
None,
Some(&run_id),
));
}
Ok(error_output(
format!("run '{run_id}' not found"),
"RUN_NOT_FOUND",
Expand Down
49 changes: 38 additions & 11 deletions agent-graph-mcp/src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -601,6 +601,7 @@ impl PersistentStore {
receipt_json TEXT NOT NULL,
bundle_json TEXT NOT NULL,
receipt_digest TEXT NOT NULL,
bundle_digest TEXT,
persisted_at TEXT NOT NULL DEFAULT (datetime('now')),
FOREIGN KEY (run_id) REFERENCES executions(run_id)
);
Expand Down Expand Up @@ -682,6 +683,7 @@ impl PersistentStore {
.map_err(|e| format!("idempotency quarantine error: {e}"))?;
for (table, column, definition) in [
("executions", "budgets_json", "TEXT"),
("terminal_receipts", "bundle_digest", "TEXT"),
("checkpoints", "checkpoint_id", "TEXT"),
("checkpoints", "graph_id", "TEXT"),
("checkpoints", "graph_version", "TEXT"),
Expand Down Expand Up @@ -1060,6 +1062,15 @@ impl PersistentStore {
let receipt: Value = serde_json::from_str(receipt_json)
.map_err(|e| format!("terminal receipt JSON error: {e}"))?;
let receipt_digest = hmac_sha256(&receipt, key);
let bundle: Value = serde_json::from_str(bundle_json)
.map_err(|e| format!("terminal bundle JSON error: {e}"))?;
// The existing receipt MAC does not cover the redacted output in the
// independently persisted bundle. Bind the entire bundle separately,
// with domain separation, before publishing it to any cold reader.
let bundle_digest = hmac_sha256(
&serde_json::json!({"schema":"graph-terminal-bundle-hmac-v1","bundle":bundle}),
key,
);
let mut conn = self.conn.lock().map_err(|e| format!("lock error: {e}"))?;
let tx = conn
.transaction()
Expand Down Expand Up @@ -1092,13 +1103,14 @@ impl PersistentStore {
return Err("injected terminal projection failure after events".into());
}
tx.execute(
"INSERT INTO terminal_receipts (run_id, receipt_json, bundle_json, receipt_digest) VALUES (?1, ?2, ?3, ?4)
"INSERT INTO terminal_receipts (run_id, receipt_json, bundle_json, receipt_digest, bundle_digest) VALUES (?1, ?2, ?3, ?4, ?5)
ON CONFLICT(run_id) DO UPDATE SET
receipt_json = CASE WHEN excluded.receipt_json = 'null' THEN terminal_receipts.receipt_json ELSE excluded.receipt_json END,
bundle_json = CASE WHEN excluded.bundle_json = 'null' THEN terminal_receipts.bundle_json ELSE excluded.bundle_json END,
receipt_digest = CASE WHEN excluded.receipt_json = 'null' THEN terminal_receipts.receipt_digest ELSE excluded.receipt_digest END,
bundle_digest = CASE WHEN excluded.receipt_json = 'null' THEN terminal_receipts.bundle_digest ELSE excluded.bundle_digest END,
persisted_at = datetime('now')",
params![run_id, receipt_json, bundle_json, receipt_digest],
params![run_id, receipt_json, bundle_json, receipt_digest, bundle_digest],
).map_err(|e| format!("terminal receipt insert error: {e}"))?;
tx.commit()
.map_err(|e| format!("terminal transaction commit error: {e}"))?;
Expand All @@ -1110,21 +1122,36 @@ impl PersistentStore {
.require_integrity_key()
.map_err(|_| "INTEGRITY_KEY_REQUIRED".to_owned())?;
let conn = self.conn.lock().map_err(|e| format!("lock error: {e}"))?;
let row: Result<(String, String), _> = conn.query_row(
"SELECT receipt_json, receipt_digest FROM terminal_receipts WHERE run_id = ?1",
let row: Result<(String, String, String, Option<String>), _> = conn.query_row(
"SELECT receipt_json, bundle_json, receipt_digest, bundle_digest FROM terminal_receipts WHERE run_id = ?1",
params![run_id],
|row| Ok((row.get(0)?, row.get(1)?)),
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
);
match row {
Ok((receipt_json, receipt_digest)) => {
Ok((receipt_json, bundle_json, receipt_digest, bundle_digest)) => {
let receipt: Value = serde_json::from_str(&receipt_json)
.map_err(|e| format!("stored receipt JSON error: {e}"))?;
if hmac_sha256(&receipt, key) != receipt_digest {
.map_err(|_| "RECEIPT_INTEGRITY_FAILURE".to_owned())?;
let bundle: Value = serde_json::from_str(&bundle_json)
.map_err(|_| "RECEIPT_INTEGRITY_FAILURE".to_owned())?;
let expected_bundle_digest = hmac_sha256(
&serde_json::json!({"schema":"graph-terminal-bundle-hmac-v1","bundle":bundle}),
key,
);
if hmac_sha256(&receipt, key) != receipt_digest
|| bundle_digest.as_deref() != Some(expected_bundle_digest.as_str())
{
// Older unbound rows cannot be upgraded by assuming the
// bundle has the same custody as a signed receipt.
return Err("RECEIPT_INTEGRITY_FAILURE".into());
}
Ok(Some(
serde_json::json!({"receipt":receipt,"receipt_digest":receipt_digest,"storage_class":"sqlite_terminal_receipt","replay_capability":"integrity_only"}),
))
Ok(Some(serde_json::json!({
"receipt":receipt,
"bundle":bundle,
"receipt_digest":receipt_digest,
"bundle_digest":bundle_digest,
"storage_class":"sqlite_terminal_receipt",
"replay_capability":"integrity_only"
})))
}
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
Err(e) => Err(format!("load terminal receipt error: {e}")),
Expand Down
106 changes: 103 additions & 3 deletions agent-graph-mcp/tests/mcp_integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -469,7 +469,7 @@ fn completed_persistent_run_is_readable_after_mcp_restart() {

let mut restarted = Mcp::new_with_data_dir(temp.path());
let recovered = restarted.call("graph_run_get", json!({"run_id":run_id}));
assert_eq!(recovered["data"]["status"], "completed");
assert_eq!(recovered["data"]["status"], "completed", "{recovered}");
assert_eq!(recovered["data"]["success"], true);
assert_eq!(
recovered["data"]["final_state"],
Expand Down Expand Up @@ -530,6 +530,106 @@ fn tampered_terminal_receipt_fails_closed_after_mcp_restart() {
assert!(!receipt.to_string().contains("never disclose"));
}

#[test]
fn v2_terminal_receipt_exposes_signed_bundle_warm_and_cold() {
let temp = tempfile::tempdir().expect("graph receipt database");
let run_id = {
let mut first = Mcp::new_with_data_dir(temp.path());
first.call(
"graph_create",
json!({
"spec":{"name":"v2-bundle","entry":"x",
"nodes":[{"id":"x","type":"passthrough"}],
"edges":[{"from":"x","to":"END"}]}
}),
);
let completed = first.call(
"graph_execute",
json!({"graph_id":"v2-bundle","input":{"request":"authenticated bundle"}}),
);
assert_eq!(completed["data"]["status"], "completed");
let run_id = completed["run_id"].as_str().expect("run ID").to_owned();
let warm = first.call("graph_run_receipt", json!({"run_id":run_id}));
assert_eq!(warm["ok"], true);
assert_eq!(
warm["data"]["receipt"]["schema"],
"agent-graph-mcp-receipt-v2"
);
assert_eq!(
warm["data"]["receipt"]["persistence_status"],
"durable_terminal"
);
assert_eq!(warm["data"]["bundle"]["payload"]["run_id"], run_id);
assert!(warm["data"]["bundle_digest"]
.as_str()
.is_some_and(|s| s.starts_with("hmac-sha256:")));
run_id
};
let mut restarted = Mcp::new_with_data_dir(temp.path());
let cold = restarted.call("graph_run_receipt", json!({"run_id":run_id}));
assert_eq!(cold["ok"], true);
assert_eq!(
cold["data"]["receipt"]["schema"],
"agent-graph-mcp-receipt-v2"
);
assert_eq!(cold["data"]["bundle"]["payload"]["run_id"], run_id);
assert!(cold["data"]["bundle_digest"]
.as_str()
.is_some_and(|s| s.starts_with("hmac-sha256:")));
}

#[test]
fn mutated_or_legacy_unbound_terminal_bundle_fails_closed() {
let temp = tempfile::tempdir().expect("graph receipt database");
let run_id = {
let mut first = Mcp::new_with_data_dir(temp.path());
first.call(
"graph_create",
json!({
"spec":{"name":"v2-tamper","entry":"x",
"nodes":[{"id":"x","type":"passthrough"}],
"edges":[{"from":"x","to":"END"}]}
}),
);
let completed = first.call(
"graph_execute",
json!({"graph_id":"v2-tamper","input":{"request":"signed bundle"}}),
);
assert_eq!(completed["data"]["status"], "completed");
completed["run_id"].as_str().expect("run ID").to_owned()
};
let db_path = temp.path().join("agent-graph.db");
{
let conn = Connection::open(&db_path).expect("database");
conn.execute(
"UPDATE terminal_receipts SET bundle_json = ?1 WHERE run_id = ?2",
rusqlite::params![
json!({"payload":{"run_id":run_id,"output":{"forged":true}}}).to_string(),
&run_id
],
)
.expect("simulate bundle substitution without key");
}
let mut restarted = Mcp::new_with_data_dir(temp.path());
let denied = restarted.call("graph_run_receipt", json!({"run_id":run_id}));
assert_eq!(denied["ok"], false);
assert_eq!(denied["error_code"], "RECEIPT_INTEGRITY_FAILURE");
assert!(!denied.to_string().contains("forged"));
drop(restarted);
{
let conn = Connection::open(&db_path).expect("database");
conn.execute(
"UPDATE terminal_receipts SET bundle_digest = NULL WHERE run_id = ?1",
rusqlite::params![&run_id],
)
.expect("simulate legacy row without bundle signature");
}
let mut restarted = Mcp::new_with_data_dir(temp.path());
let denied = restarted.call("graph_run_receipt", json!({"run_id":run_id}));
assert_eq!(denied["ok"], false);
assert_eq!(denied["error_code"], "RECEIPT_INTEGRITY_FAILURE");
}

#[test]
fn terminal_events_are_readable_after_mcp_restart() {
let temp = tempfile::tempdir().expect("temp graph database");
Expand Down Expand Up @@ -1463,8 +1563,8 @@ fn durable_checkpoint_approval_survives_restart_and_resumes_exact_bound_checkpoi
restarted.call("graph_run_wait", json!({"run_id":run_id,"timeout_ms":5000}));
assert_eq!(completed["data"]["status"], "completed");
assert_eq!(
completed["data"]["receipt"]["checkpoint"]["checkpoint_id"],
checkpoint_id
completed["data"]["receipt"]["checkpoint"]["checkpoint_id"], checkpoint_id,
"{completed}"
);
assert_eq!(
completed["data"]["receipt"]["approval"]["approval_id"],
Expand Down
Loading