From 20dac0234fbb2c3ea4e7ca623ead6eb45c4ecc48 Mon Sep 17 00:00:00 2001 From: Josh Stevenson Date: Sun, 22 Nov 2026 22:14:25 -0600 Subject: [PATCH 1/9] feat(graph): stamp new terminal receipts v2 for Ares2 custody contract --- agent-graph-mcp/src/run_manager.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/agent-graph-mcp/src/run_manager.rs b/agent-graph-mcp/src/run_manager.rs index b9ccf709..ed65adf4 100644 --- a/agent-graph-mcp/src/run_manager.rs +++ b/agent-graph-mcp/src/run_manager.rs @@ -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" }, From 57bf7f49e3faed6bd776592c1947f5940c382309 Mon Sep 17 00:00:00 2001 From: Josh Stevenson Date: Sun, 22 Nov 2026 22:14:42 -0600 Subject: [PATCH 2/9] feat(graph): MAC-bind durable bundles and fail closed on legacy unsigned bundle rows --- agent-graph-mcp/src/store.rs | 49 ++++++++++++++++++++++++++++-------- 1 file changed, 38 insertions(+), 11 deletions(-) diff --git a/agent-graph-mcp/src/store.rs b/agent-graph-mcp/src/store.rs index 848ce884..506b3b61 100644 --- a/agent-graph-mcp/src/store.rs +++ b/agent-graph-mcp/src/store.rs @@ -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) ); @@ -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"), @@ -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() @@ -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}"))?; @@ -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), _> = 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}")), From a574861e4bdaae5e512b3d3b521c4619a82b8190 Mon Sep 17 00:00:00 2001 From: Josh Stevenson Date: Sun, 22 Nov 2026 22:14:56 -0600 Subject: [PATCH 3/9] fix(graph): prefer signed durable terminal receipt over volatile cache in warm and cold reads --- agent-graph-mcp/src/server.rs | 33 +++++++++++++++++++-------------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/agent-graph-mcp/src/server.rs b/agent-graph-mcp/src/server.rs index 88fc8dde..99c4654a 100644 --- a/agent-graph-mcp/src/server.rs +++ b/agent-graph-mcp/src/server.rs @@ -2483,19 +2483,9 @@ impl AgentGraphServer { &self, Parameters(RunReceiptParams { run_id }): Parameters, ) -> Result, 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)) => { @@ -2504,7 +2494,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", )); } @@ -2517,6 +2507,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", From 71299092b8b400f0901ef952dbbb5ab65328d875 Mon Sep 17 00:00:00 2001 From: Josh Stevenson Date: Sun, 22 Nov 2026 22:15:15 -0600 Subject: [PATCH 4/9] test(graph): warm/cold v2 signed-bundle custody and tamper/legacy fail-closed --- agent-graph-mcp/tests/mcp_integration.rs | 82 ++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/agent-graph-mcp/tests/mcp_integration.rs b/agent-graph-mcp/tests/mcp_integration.rs index b1306e78..6c3f753e 100644 --- a/agent-graph-mcp/tests/mcp_integration.rs +++ b/agent-graph-mcp/tests/mcp_integration.rs @@ -530,6 +530,88 @@ 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"); From 6044afc327d15fba965176e052f11d284f8c8d98 Mon Sep 17 00:00:00 2001 From: Josh Stevenson Date: Sun, 22 Nov 2026 22:17:54 -0600 Subject: [PATCH 5/9] style(graph): apply exact rustfmt diffs from failed workspace CI --- agent-graph-mcp/tests/mcp_integration.rs | 54 ++++++++++++++++-------- 1 file changed, 36 insertions(+), 18 deletions(-) diff --git a/agent-graph-mcp/tests/mcp_integration.rs b/agent-graph-mcp/tests/mcp_integration.rs index 6c3f753e..e4a4203a 100644 --- a/agent-graph-mcp/tests/mcp_integration.rs +++ b/agent-graph-mcp/tests/mcp_integration.rs @@ -530,17 +530,19 @@ 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"}]} - })); + 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"}}), @@ -549,19 +551,30 @@ fn v2_terminal_receipt_exposes_signed_bundle_warm_and_cold() { 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"]["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() + 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"]["receipt"]["schema"], + "agent-graph-mcp-receipt-v2" + ); assert_eq!(cold["data"]["bundle"]["payload"]["run_id"], run_id); - assert!(cold["data"]["bundle_digest"].as_str() + assert!(cold["data"]["bundle_digest"] + .as_str() .is_some_and(|s| s.starts_with("hmac-sha256:"))); } @@ -570,11 +583,14 @@ 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"}]} - })); + 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"}}), @@ -591,7 +607,8 @@ fn mutated_or_legacy_unbound_terminal_bundle_fails_closed() { json!({"payload":{"run_id":run_id,"output":{"forged":true}}}).to_string(), &run_id ], - ).expect("simulate bundle substitution without key"); + ) + .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})); @@ -604,7 +621,8 @@ fn mutated_or_legacy_unbound_terminal_bundle_fails_closed() { conn.execute( "UPDATE terminal_receipts SET bundle_digest = NULL WHERE run_id = ?1", rusqlite::params![&run_id], - ).expect("simulate legacy row without bundle signature"); + ) + .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})); From ff6d2d47cc29476c70932f220795216059450158 Mon Sep 17 00:00:00 2001 From: Josh Stevenson Date: Sun, 22 Nov 2026 22:18:13 -0600 Subject: [PATCH 6/9] ci(graph): exact-head focused Rust terminal receipt and bundle custody gate --- .github/workflows/ares2-graph-custody.yml | 33 +++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 .github/workflows/ares2-graph-custody.yml diff --git a/.github/workflows/ares2-graph-custody.yml b/.github/workflows/ares2-graph-custody.yml new file mode 100644 index 00000000..cf461dd4 --- /dev/null +++ b/.github/workflows/ares2-graph-custody.yml @@ -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 From 50a9ef0561b8235d1d7d03f61200c9bd3a3bae19 Mon Sep 17 00:00:00 2001 From: Josh Stevenson Date: Sun, 22 Nov 2026 22:20:06 -0600 Subject: [PATCH 7/9] test(graph): preserve complete diagnostic response on cold lifecycle regression --- agent-graph-mcp/tests/mcp_integration.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/agent-graph-mcp/tests/mcp_integration.rs b/agent-graph-mcp/tests/mcp_integration.rs index e4a4203a..7127db70 100644 --- a/agent-graph-mcp/tests/mcp_integration.rs +++ b/agent-graph-mcp/tests/mcp_integration.rs @@ -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"], @@ -1564,7 +1564,8 @@ fn durable_checkpoint_approval_survives_restart_and_resumes_exact_bound_checkpoi assert_eq!(completed["data"]["status"], "completed"); assert_eq!( completed["data"]["receipt"]["checkpoint"]["checkpoint_id"], - checkpoint_id + checkpoint_id, + "{completed}" ); assert_eq!( completed["data"]["receipt"]["approval"]["approval_id"], From b13bf7daa5d0ce558679bd44dc87a1613a9e0a3e Mon Sep 17 00:00:00 2001 From: Josh Stevenson Date: Sun, 22 Nov 2026 22:20:45 -0600 Subject: [PATCH 8/9] style(graph): normalize cold recovery diagnostic assertion with rustfmt --- agent-graph-mcp/tests/mcp_integration.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/agent-graph-mcp/tests/mcp_integration.rs b/agent-graph-mcp/tests/mcp_integration.rs index 7127db70..6ba33c7b 100644 --- a/agent-graph-mcp/tests/mcp_integration.rs +++ b/agent-graph-mcp/tests/mcp_integration.rs @@ -1563,8 +1563,7 @@ 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!( From c400437d3064ffcc1fec5016acb64d0cb5b4ab5c Mon Sep 17 00:00:00 2001 From: Josh Stevenson Date: Sun, 22 Nov 2026 22:24:06 -0600 Subject: [PATCH 9/9] fix(graph): single terminal persistence owner; wait for durable acknowledgement instead of racing writes --- agent-graph-mcp/src/server.rs | 49 +++++++++++++++++++++-------------- 1 file changed, 29 insertions(+), 20 deletions(-) diff --git a/agent-graph-mcp/src/server.rs b/agent-graph-mcp/src/server.rs index 99c4654a..c4c4b1e9 100644 --- a/agent-graph-mcp/src/server.rs +++ b/agent-graph-mcp/src/server.rs @@ -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()) {