.NET / SQL / Enterprise Engineering

Human Review Gates and Machine-Executable Falsification for Agent Memory

Report summary

The transition from stateless, single-turn conversational models to autonomous agentic systems relies heavily on the implementation of persistent memory architectures. Memory enables artificial intelligence systems to operate with continuity across extended temporal horizons, tracking multi-step wor

Status
Research archive item
Category
.NET / SQL / Enterprise Engineering
Length
5,060 words
Reading time
23 minutes
Report type
evaluation

Key topics

  • .NET / SQL / Enterprise Engineering
  • .NET
  • SQL
  • Enterprise Engineering
  • AI
  • AI Memory
  • Agentic Web
  • Python
  • Runtime

Research provenance

Archive status
Research archive item
Content identity
sha256:2cc4e74a8661948bfb62d70e750dd7f455af6f7c7a013a3d8d96aff867bb929d

For citation, use the report title and canonical URL. Archival presence does not establish authorship or promote report statements into portfolio evidence.

This page renders the archived Markdown as safe, formatted HTML. It is background research and does not become a portfolio claim without evidence review.

Full report

On this page

Executive Summary

The transition from stateless, single-turn conversational models to autonomous agentic systems relies heavily on the implementation of persistent memory architectures. Memory enables artificial intelligence systems to operate with continuity across extended temporal horizons, tracking multi-step workflows, maintaining contextual awareness across discrete sessions, and executing procedural corrections based on historical outcomes1. However, the introduction of autonomous state persistence fundamentally expands the threat landscape. Unmanaged or unsupervised memory introduces severe operational and security risks, including context drift, implicit learning of hallucinatory logic, unauthorized data leakage across isolation boundaries, and the escalation of transient prompt-injection attacks into persistent, autonomous threats2. To mitigate these risks in enterprise-grade deployments, this research report details the architectural design of a deterministic, human-in-the-loop (HITL) review gateway and lifecycle-management system for generalized memory patterns. These memory patterns are extracted offline from successful and failed agent trajectories using Fused Gromov-Wasserstein (FGW) graph alignment, a generalized optimal transport metric that captures both structural topology and semantic node features4. Because FGW and other optimal transport algorithms yield probabilistic or algorithmically inferred distance metrics and alignments7, their output must be treated as untrusted analytical findings rather than operational truth. This architecture enforces a strict governance protocol where no cross-task memory pattern may enter an agent's active memory without passing automated validation and explicit authorization by a qualified human reviewer. Furthermore, every approved pattern must encapsulate deterministic, machine-executable falsification conditions written in the Common Expression Language (CEL). These conditions allow the runtime agent gateway to dynamically quarantine or suspend the memory pattern if real-time environmental evidence contradicts the foundational assumptions of the aligned graph9. Supported by an ASP.NET Core Minimal API layer, Entity Framework Core optimistic concurrency controls, and the transactional Outbox pattern, this system ensures high-fidelity, auditable, and immutable state management for AI agent memory11.

Governance Principles

The architecture operates upon a foundational set of AI governance and safety engineering principles that dictate system behavior, state transitions, and boundary enforcement. The primary axiom of this system is that probabilistic output is inherently untrusted. Any memory pattern inferred algorithmically—whether an action sequence, a common subgraph, a correction plan, or an optimal transport alignment—represents a statistical approximation of a successful trajectory3. Consequently, such patterns require a deterministic validation gateway. Natural-language caveats are insufficient for enforcing runtime safety; therefore, deterministic falsifiability is mandated10. Every proposed memory artifact must contain machine-evaluable conditions that, when true, automatically suspend the application of the pattern without relying on the non-deterministic reasoning of a Large Language Model (LLM) during the execution loop. Provenance precedes persistence in this architecture. Memory is only committed to the active database when it carries clear, immutable metadata tracing it back to its source solver, the specific solver configuration (such as the FGW alpha fusion weight or entropic regularization parameters), and the exact evidence graphs from which it was derived3. This provenance is secured by strict authorization boundaries. While an LLM or an automated heuristic may propose, filter, or summarize memory artifacts, the final state transition to an approved status must be executed by an authenticated, cryptographically verifiable human identity, adhering to the "Human-in-the-Loop" (HITL) paradigm rather than "Human-on-the-Loop" (HOTL) or "Human-out-of-the-Loop" (HOOL) models for high-risk systemic updates10. Finally, the system enforces immutable versions. Once a human reviewer approves an artifact, it cannot be silently modified. Any material change to its graph topology, edit path, or falsification conditions automatically generates a superseded version, thereby resetting the entire review lifecycle and enforcing a new audit trail3.

1. Review Artifact Schema

The analytical output of the offline graph-alignment process is encapsulated within a structured artifact known as a CrossTaskAnalyticalFinding. When evaluating trajectories, the Fused Gromov-Wasserstein (FGW) framework calculates a distance metric by combining feature-based optimal transport costs with structural graph discrepancies, facilitating the generation of a minimal Graph Edit Distance (GED) or an edit path containing node and edge insertions, deletions, and substitutions5. This schema captures these components alongside strict governance metadata.

JSON Schema Definition

The following JSON Schema enforces the structural integrity of the proposed memory pattern before it reaches the human review queue. It mandates the use of URIs for evidence objects to prevent the injection of unrestricted binary content, ensuring the database remains performant and secure3.

JSON { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://governance.internal/schemas/cross-task-analytical-finding.json", "title": "CrossTaskAnalyticalFinding", "type": "object", "required": \[ "artifactId", "tenantId", "fleetScope", "sourceTask", "targetTask", "sourceGraphVersion", "targetGraphVersion", "matchingSubgraph", "proposedGraphEditPath", "proposedUniversalActionLogic", "alignmentScore", "solverProvenance", "falsificationConditions", "lifecycleState", "contentHash" \], "properties": { "artifactId": { "type": "string", "format": "uuid" }, "tenantId": { "type": "string", "format": "uuid" }, "fleetScope": { "type": "array", "items": { "type": "string" }, "minItems": 1 }, "sourceTask": { "type": "string" }, "targetTask": { "type": "string" }, "sourceGraphVersion": { "type": "string" }, "targetGraphVersion": { "type": "string" }, "matchingSubgraph": { "type": "object", "properties": { "nodes": { "type": "array", "items": { "type": "string" } }, "edges": { "type": "array", "items": { "type": "string" } } }, "required": \["nodes", "edges"\] }, "proposedGraphEditPath": { "type": "array", "items": { "type": "object", "properties": { "operation": { "enum": \["InsertNode", "DeleteNode", "SubstituteNode", "InsertEdge", "DeleteEdge"\] }, "targetId": { "type": "string" }, "cost": { "type": "number", "minimum": 0 } }, "required": \["operation", "targetId", "cost"\] } }, "proposedUniversalActionLogic": { "type": "string" }, "alignmentScore": { "type": "object", "properties": { "fgwDistance": { "type": "number", "minimum": 0 }, "featureScore": { "type": "number", "minimum": 0 }, "structuralScore": { "type": "number", "minimum": 0 } }, "required": \["fgwDistance", "featureScore", "structuralScore"\] }, "solverProvenance": { "type": "object", "properties": { "solverVersion": { "type": "string" }, "alphaFusionWeight": { "type": "number", "minimum": 0, "maximum": 1 }, "entropicRegularization": { "type": "number", "minimum": 0 } }, "required": \["solverVersion", "alphaFusionWeight"\] }, "evidenceReferences": { "type": "array", "items": { "type": "string", "format": "uri" } }, "topologySnapshotReferences": { "type": "array", "items": { "type": "string", "format": "uri" } }, "featureModelVersion": { "type": "string" }, "riskClassification": { "enum": \["Low", "Moderate", "High", "Critical"\] }, "confidence": { "type": "number", "minimum": 0, "maximum": 1 }, "knownLimitations": { "type": "array", "items": { "type": "string" } }, "falsificationConditions": { "type": "array", "items": { "type": "object", "properties": { "expression": { "type": "string" }, "description": { "type": "string" } }, "required": \["expression", "description"\] }, "minItems": 1 }, "requiredReviewerQualifications": { "type": "array", "items": { "type": "string" } }, "expirationUtc": { "type": "string", "format": "date-time" }, "lifecycleState": { "type": "string" }, "creationTimestampUtc": { "type": "string", "format": "date-time" }, "decisionTimestampUtc": { "type": \["string", "null"\], "format": "date-time" }, "contentHash": { "type": "string" }, "digitalSignature": { "type": "string" } } }

Artifact Examples

The following tables and data structures illustrate the distinction between a valid artifact that adheres to the governance constraints and an invalid artifact that triggers the automated validation tripwires. Example 1: Valid Artifact This artifact correctly utilizes universal resource identifiers (URIs) for external evidence, specifies solver provenance parameters vital for reproducing the Fused Gromov-Wasserstein alignment, and features a deterministically evaluable falsification expression.

JSON { "artifactId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "tenantId": "c3d4e5f6-1122-3344-5566-778899aabbcc", "fleetScope": \["cloud-infrastructure-ops"\], "sourceTask": "deploy-aks-cluster", "targetTask": "deploy-eks-cluster", "sourceGraphVersion": "v1.4.2", "targetGraphVersion": "v1.4.2", "matchingSubgraph": { "nodes": \["node\_auth\_init", "node\_network\_config"\], "edges": \["edge\_auth\_to\_net"\] }, "proposedGraphEditPath": \[ { "operation": "SubstituteNode", "targetId": "node\_api\_endpoint", "cost": 0.5 } \], "proposedUniversalActionLogic": "IF infrastructure\_provider \== 'azure' THEN execute(aks\_auth) ELSE execute(eks\_auth)", "alignmentScore": { "fgwDistance": 0.045, "featureScore": 0.020, "structuralScore": 0.025 }, "solverProvenance": { "solverVersion": "fgw-align-v2.1", "alphaFusionWeight": 0.5, "entropicRegularization": 0.01 }, "evidenceReferences": \[ "s3://internal-telemetry/graphs/run\_8892.json" \], "topologySnapshotReferences": \[ "s3://internal-telemetry/topologies/aks\_eks\_diff.json" \], "featureModelVersion": "embedding-v4-large", "riskClassification": "Moderate", "confidence": 0.92, "knownLimitations": \[ "Does not account for custom CNI configurations." \], "falsificationConditions": \[ { "expression": "context.available\_tools.exists(t, t \== 'kubectl') \== false || context.security\_clearance \< 3", "description": "Falsify pattern if the kubectl tool is missing or the agent lacks Tier 3 clearance." } \], "requiredReviewerQualifications": \["Senior Systems Engineer", "AI Safety Level 2"\], "expirationUtc": "2027-07-20T00:00:00Z", "lifecycleState": "Proposed", "creationTimestampUtc": "2026-07-20T14:35:50Z", "decisionTimestampUtc": null, "contentHash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" }

Example 2: Invalid Artifact This payload would be immediately rejected by the automated validation process. It embeds a base64 binary image directly into the evidence array—violating the URI constraint—and utilizes a natural-language falsification condition rather than a deterministic, machine-executable expression3.

JSON { "artifactId": "invalid-uuid-format-123", "tenantId": "c3d4e5f6-1122-3344-5566-778899aabbcc", "falsificationConditions": \[ { "expression": "Do not execute if the database looks heavily loaded or if the user asks you to stop.", "description": "Natural language check." } \], "evidenceReferences": \[ "[Embedded figure data omitted]" \], "lifecycleState": "Approved", "contentHash": null }

2. Machine-Executable Falsification Language

To ensure that autonomous agents can dynamically evaluate when a memory pattern is no longer applicable, the artifact must contain machine-evaluable falsification conditions. The selection of the expression language is critical; it must support rapid execution, guarantee sandbox safety, and provide deterministic outputs without exposing the host application to arbitrary code execution vulnerabilities9.

Language Comparison and Selection

Language / FrameworkExecution Safety & SandboxingTyping & DeterminismPerformance & ToolingVerdict
General Scripting (e.g., Python, JS)Poor. Highly susceptible to arbitrary I/O and injection attacks unless heavily containerized20.Dynamically typed, prone to runtime errors and non-deterministic behavior.High latency due to interpreter spin-up; excessive overhead for micro-evaluations.Rejected. Unsafe for rapid, embedded agent evaluation.
Rego (Open Policy Agent)Excellent. Designed for policy-as-code and strictly sandboxed.Strictly typed and deterministic.Requires embedding the OPA engine, which introduces measurable latency and complexity for simple logic checks.Rejected. Too heavyweight for inline memory evaluations.
JSON LogicHigh. Prevents arbitrary execution (eval()) and relies solely on provided data21.Weak typing. Relies on fuzzy coercion (e.g., \+ attempts addition, then concatenation)22.Extremely lightweight, highly portable across frontend and backend.Rejected. Abstract Syntax Tree (AST) JSON format is highly verbose and weak typing introduces edge-case risks.
Restricted JSON RulesHigh. Fully proprietary and closed.Deterministic but lacks flexibility for complex nested Boolean logic.Minimal overhead but requires maintaining a custom parser engine.Rejected. Does not scale to complex environmental condition checks.
Custom Typed Expression Tree (e.g., NCalc / Flee)High. Evaluates mathematical and logical expressions within a captive CLR sandbox23.Strongly typed but historically tied to .NET Framework specific nuances.Fast execution via IL emission, but lacks widespread cross-language standard support.Rejected. Maintenance overhead of custom parsers outweighs benefits.
Common Expression Language (CEL)Exceptional. Explicitly designed by Google for non-Turing complete, safe embedded evaluation9.Strictly typed. Fails during static compilation if types mismatch.Microsecond execution time. Native support in Kubernetes; C\# ports available (CEL.NET)18.Recommended. Best balance of safety, speed, and strict typing.

Recommendation: The Common Expression Language (CEL) is the mandated framework. It evaluates safely and quickly in performance-critical paths (nanoseconds to microseconds), natively prevents arbitrary I/O, and enforces strict typing that allows syntax errors to be caught during the offline validation phase prior to human review9.

Expression Schema and C# Evaluation Interface

The system relies on a bounded execution context. Missing data in the context defaults to a fail-closed response, preventing the agent from proceeding with unverified assumptions. Numeric precision relies on IEEE 754 standards, and all temporal comparisons require UTC localization.

C\# namespace AgentGovernance.Falsification { using System; using System.Collections.Generic; using System.Threading.Tasks;

/// \<summary\> /// Represents the deterministic runtime context provided by the agent gateway. /// \</summary\> public record AgentRuntimeContext( string TargetObject, List\<string\> AvailableTools, double ConfidenceThreshold, int SecurityClassification, Dictionary\<string, object\> EnvironmentalState, DateTimeOffset CurrentTimeUtc );

/// \<summary\> /// Represents the strict outcome of a falsification check. /// \</summary\> public record FalsificationResult(bool IsFalsified, string Reason, bool HasError);

/// \<summary\> /// Core interface for evaluating CEL expressions against the agent's runtime state. /// \</summary\> public interface IFalsificationEvaluator { /// \<summary\> /// Statically validates a CEL expression for syntax and type safety. /// \</summary\> /// \<param name="expression"\>The CEL expression string.\</param\> /// \<returns\>True if the syntax is valid and type-safe.\</returns\> bool ValidateSyntax(string expression);

/// \<summary\> /// Evaluates a pre-validated CEL expression against the provided runtime context. /// \</summary\> /// \<param name="expression"\>The CEL expression to evaluate.\</param\> /// \<param name="context"\>The state of the agent environment.\</param\> /// \<returns\>A FalsificationResult indicating if the memory pattern should be quarantined.\</returns\> ValueTask\<FalsificationResult\> EvaluateAsync(string expression, AgentRuntimeContext context); }

/// \<summary\> /// Implementation of the falsification evaluator using a sandboxed CEL engine. /// \</summary\> public class CelFalsificationEvaluator : IFalsificationEvaluator { public bool ValidateSyntax(string expression) { // In production, this invokes the CEL parser to ensure abstract syntax tree integrity. // Rejects dynamically typed comparisons or unrecognized functions. if (string.IsNullOrWhiteSpace(expression)) return false; return true; }

public async ValueTask\<FalsificationResult\> EvaluateAsync(string expression, AgentRuntimeContext context) { try { // Simulate bounded execution. // Missing variables throw specific evaluation exceptions in CEL, which are caught here. bool evaluationResult \= await SimulateCelExecutionAsync(expression, context);

return new FalsificationResult( IsFalsified: evaluationResult, Reason: evaluationResult ? "Runtime evidence matched falsification criteria." : "Criteria not met.", HasError: false ); } catch (Exception ex) { // Fail-closed mechanism: If evaluation throws an error (e.g., missing data, type mismatch), // the pattern is considered falsified for safety. return new FalsificationResult(IsFalsified: true, Reason: $"Evaluation Error: {ex.Message}", HasError: true); } }

private ValueTask\<bool\> SimulateCelExecutionAsync(string expression, AgentRuntimeContext context) { // Simulated integration with CEL.NET or similar abstract syntax tree evaluator. return ValueTask.FromResult(false); } } }

3. Lifecycle State Machine

A graph-derived memory pattern traverses a highly controlled, auditable lifecycle. This state machine restricts transitions based on the current state, the required role of the initiator, and specific guard conditions.

State Transition Specification

Current StateTarget StateInitiating RoleGuard / ConditionSide Effect / Audit Event
ProposedReadyForReviewSystemPasses automated validation.Triggers ValidationPassedEvent.
ProposedValidationFailedSystemFails schema, hash, or CEL checks.Terminal state. Triggers ValidationFailedEvent.
ReadyForReviewUnderReviewReviewerETag match; reviewer authenticated.Assigns reviewer ID to artifact.
UnderReviewChangesRequestedReviewerReviewer submits modification notes.Unlocks artifact for solver refinement.
UnderReviewRejectedReviewerReviewer explicitly denies.Terminal state. Triggers ArtifactRejectedEvent.
UnderReviewApprovedReviewerFalsification rules validated; cryptographic signature appended.Locks artifact from mutation.
ApprovedCommittingSystemOutbox transaction initiated.Inserts ArtifactCommittedEvent in DB.
CommittingCommittedSystemEvent successfully published to bus.Pattern enters active agent memory.
CommittedSuspendedAdminAnomaly detected in telemetry.Broadcasts CacheInvalidationEvent to agents.
SuspendedCommittedAdminInvestigation clears anomaly.Re-publishes artifact to active memory.
CommittedSupersededSystemNewer graph alignment overrides old pattern.Terminal state. Old pattern removed from active cache.
CommittedRevokedAdminCatastrophic failure or policy violation.Terminal state. Triggers TombstoneEvent.

Complete C# State Machine Implementation

The following implementation defines the state machine without relying on third-party libraries, ensuring maximum transparency, minimal dependencies, and seamless integration with the ASP.NET Core environment. Display attributes define human-readable strings for the dashboard.

C\# namespace AgentGovernance.StateMachine { using System; using System.ComponentModel.DataAnnotations;

/// \<summary\> /// Represents the lifecycle states of a CrossTaskAnalyticalFinding. /// \</summary\> public enum ArtifactState { \[Display(Name \= "Proposed")\] Proposed \= 0, \[Display(Name \= "Validation Failed")\] ValidationFailed \= 1, \[Display(Name \= "Ready For Review")\] ReadyForReview \= 2, \[Display(Name \= "Under Review")\] UnderReview \= 3, \[Display(Name \= "Changes Requested")\] ChangesRequested \= 4, \[Display(Name \= "Rejected")\] Rejected \= 5, \[Display(Name \= "Approved")\] Approved \= 6, \[Display(Name \= "Committing")\] Committing \= 7, \[Display(Name \= "Committed")\] Committed \= 8, \[Display(Name \= "Suspended")\] Suspended \= 9, \[Display(Name \= "Superseded")\] Superseded \= 10, \[Display(Name \= "Revoked")\] Revoked \= 11 }

/// \<summary\> /// Exception thrown when an invalid state transition is attempted. /// \</summary\> public class InvalidArtifactTransitionException : Exception { public InvalidArtifactTransitionException(string message) : base(message) { } }

/// \<summary\> /// Manages deterministic state transitions for memory artifacts. /// \</summary\> public static class ArtifactLifecycleManager { /// \<summary\> /// Evaluates if a transition is permitted and executes it, recording the side effect. /// \</summary\> /// \<param name="currentState"\>The current state of the artifact.\</param\> /// \<param name="targetState"\>The requested state.\</param\> /// \<param name="userRole"\>The role of the user attempting the transition.\</param\> /// \<returns\>The resulting state if permitted.\</returns\> /// \<exception cref="InvalidArtifactTransitionException"\>Thrown when the transition violates governance rules.\</exception\> public static ArtifactState Transition(ArtifactState currentState, ArtifactState targetState, string userRole) { bool isValid \= (currentState, targetState, userRole) switch { (ArtifactState.Proposed, ArtifactState.ReadyForReview, "System") \=\> true, (ArtifactState.Proposed, ArtifactState.ValidationFailed, "System") \=\> true,

(ArtifactState.ReadyForReview, ArtifactState.UnderReview, "Reviewer") \=\> true, (ArtifactState.UnderReview, ArtifactState.ChangesRequested, "Reviewer") \=\> true, (ArtifactState.UnderReview, ArtifactState.Rejected, "Reviewer") \=\> true, (ArtifactState.UnderReview, ArtifactState.Approved, "Reviewer") \=\> true,

(ArtifactState.Approved, ArtifactState.Committing, "System") \=\> true, (ArtifactState.Committing, ArtifactState.Committed, "System") \=\> true,

(ArtifactState.Committed, ArtifactState.Suspended, "Admin") \=\> true, (ArtifactState.Suspended, ArtifactState.Committed, "Admin") \=\> true,

(ArtifactState.Committed, ArtifactState.Superseded, "System") \=\> true, (ArtifactState.Suspended, ArtifactState.Revoked, "Admin") \=\> true, (ArtifactState.Committed, ArtifactState.Revoked, "Admin") \=\> true,

\_ \=\> false };

if (\!isValid) { throw new InvalidArtifactTransitionException( $"Transition from {currentState} to {targetState} is not permitted for role {userRole}." ); }

return targetState; }

/// \<summary\> /// Determines if the current state is considered terminal. /// \</summary\> /// \<param name="state"\>The state to check.\</param\> /// \<returns\>True if terminal.\</returns\> public static bool IsTerminal(ArtifactState state) { return state is ArtifactState.ValidationFailed or ArtifactState.Rejected or ArtifactState.Superseded or ArtifactState.Revoked; } } }

4. Automated Validation

The automated validation layer acts as a strict programmatic filter ensuring that safety engineers only review logically sound, cryptographically intact, and syntactically correct proposals. Blocking Failures: Any violation in this category transitions the artifact to ValidationFailed, halting the lifecycle.

  • JSON Schema Violation: The artifact lacks required properties (e.g., missing tenantId or alignmentScore).
  • Falsification Syntax Errors: The CEL engine fails to compile the string into a valid Abstract Syntax Tree (AST), indicating type mismatches or syntax errors18.
  • Provenance Irreproducibility: Missing solver version or required hyperparameters (alpha weight, entropic regularization) rendering the Fused Gromov-Wasserstein alignment irreproducible5.
  • Binary Object Detection: Evidence fields containing data: protocols (e.g., base64 strings) instead of verified external URIs, violating storage limits and security policies3.
  • Edit-Plan Inconsistency: The proposed node operations in the Graph Edit Path reference nodes that do not exist within the specified topological snapshot references17.

Non-Blocking Warnings: These issues are logged to the audit trail and flagged in the UI, but the artifact transitions to ReadyForReview.

  • Duplicate Proposals: An identical structural alignment was previously reviewed and rejected. The UI surfaces the historical context to the reviewer.
  • Score Imbalances: The FGW distance indicates a strong structural match but a remarkably poor feature score (e.g., featureScore \< 0.05 while structuralScore \> 0.80), implying a topological similarity with entirely disconnected semantic context7.

5. Persistence Model and Commit/Rollback Architecture

Distributed memory systems suffer from the dual-write problem: attempting to update a local database state while simultaneously publishing a message to a distributed agent queue can result in split-brain data corruption if one system fails13. To resolve this, the architecture employs the Transactional Outbox Pattern alongside Optimistic Concurrency Control via Entity Framework Core11.

Persistence Model

The GovernanceDbContext utilizes SQL Server's native rowversion mapped to a byte\[\] property in C\#. This guarantees that concurrent updates throw a DbUpdateConcurrencyException, enforcing strict ETag comparison during human review11.

C\# namespace AgentGovernance.Data { using System; using System.ComponentModel.DataAnnotations; using AgentGovernance.StateMachine; using Microsoft.EntityFrameworkCore;

public class MemoryArtifact { public Guid Id { get; set; } \= Guid.NewGuid();

\[MaxLength(50)\] public string TenantId { get; set; }

public ArtifactState State { get; set; }

public string ContentJson { get; set; } public string ContentHash { get; set; }

\[Timestamp\] // Triggers native SQL Server rowversion for optimistic concurrency public byte\[\] RowVersion { get; set; } }

public class OutboxMessage { public Guid Id { get; set; } \= Guid.NewGuid(); public string EventType { get; set; } public string Payload { get; set; } public DateTime CreatedAtUtc { get; set; } \= DateTime.UtcNow; public DateTime? ProcessedAtUtc { get; set; } }

public class GovernanceDbContext : DbContext { public DbSet\<MemoryArtifact\> Artifacts { get; set; } public DbSet\<OutboxMessage\> OutboxMessages { get; set; }

public GovernanceDbContext(DbContextOptions\<GovernanceDbContext\> options) : base(options) { }

protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity\<MemoryArtifact\>() .Property(p \=\> p.RowVersion) .IsRowVersion();

modelBuilder.Entity\<OutboxMessage\>() .HasIndex(m \=\> m.ProcessedAtUtc); // Optimize polling query } } }

Commit and Rollback (The Outbox Workflow)

The atomic promotion workflow ensures that an artifact transitioning from Approved to Committed is recorded safely.

1. The API verifies the current state and ETag11.

2. A single SQL transaction encapsulates the state change to Committing and the insertion of an OutboxMessage containing the ArtifactCommitted event29.

3. If the database commit fails, an automatic rollback occurs, leaving the artifact in the Approved state.

4. A background IHostedService continuously polls the OutboxMessage table, dispatching pending events to the agent messaging bus (e.g., Kafka or Service Bus). Upon successful dispatch, it marks the event as processed and finalizes the artifact state to Committed13.

6. ASP.NET Core Minimal API Implementation

The API layer relies on Minimal APIs, leveraging custom filters to guarantee idempotency. Idempotency is vital; it ensures that a client retrying a PUT request due to a network timeout does not accidentally alter the system state twice or corrupt audit logs32.

API Endpoints

This implementation provides the endpoints required to interact with the lifecycle state machine, enforce ETag concurrency, and handle problem details.

C\# namespace AgentGovernance.Api { using AgentGovernance.Data; using AgentGovernance.StateMachine; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Caching.Distributed; using System; using System.Linq; using System.Text.Json; using System.Threading.Tasks;

public static class GovernanceEndpoints { public static void MapArtifactEndpoints(this WebApplication app) { var group \= app.MapGroup("/api/artifacts") .RequireAuthorization("ReviewerPolicy");

// 1\. List Review Queues (Pagination & Filtering) group.MapGet("/", async ( \[FromQuery\] int page, \[FromQuery\] int size, \[FromQuery\] string tenantId, GovernanceDbContext db) \=\> { var query \= db.Artifacts.Where(a \=\> a.State \== ArtifactState.ReadyForReview); if (\!string.IsNullOrEmpty(tenantId)) query \= query.Where(a \=\> a.TenantId \== tenantId);

var items \= await query.Skip((page \- 1) \* size).Take(size).ToListAsync(); return Results.Ok(items); });

// 2\. Retrieve One Artifact group.MapGet("/{id:guid}", async (Guid id, GovernanceDbContext db) \=\> { var artifact \= await db.Artifacts.FindAsync(id); return artifact is not null ? Results.Ok(artifact) : Results.NotFound(); });

// 3\. Claim Artifact group.MapPut("/{id:guid}/claim", async (Guid id, GovernanceDbContext db, HttpContext ctx) \=\> { var artifact \= await db.Artifacts.FindAsync(id); if (artifact \== null) return Results.NotFound();

try { artifact.State \= ArtifactLifecycleManager.Transition(artifact.State, ArtifactState.UnderReview, "Reviewer"); await db.SaveChangesAsync(); return Results.Ok(new { artifact.Id, ETag \= Convert.ToBase64String(artifact.RowVersion) }); } catch (InvalidArtifactTransitionException ex) { return Results.Problem(detail: ex.Message, statusCode: 409); } }).AddEndpointFilter\<IdempotencyFilter\>();

// 4\. Approve Artifact (with Optimistic Concurrency / ETags) group.MapPut("/{id:guid}/approve", async (Guid id, HttpContext ctx, GovernanceDbContext db) \=\> { var artifact \= await db.Artifacts.FindAsync(id); if (artifact \== null) return Results.NotFound();

string clientEtag \= ctx.Request.Headers\["If-Match"\].ToString(); string currentEtag \= Convert.ToBase64String(artifact.RowVersion); if (clientEtag \!= currentEtag) return Results.StatusCode(StatusCodes.Status412PreconditionFailed);

try { artifact.State \= ArtifactLifecycleManager.Transition(artifact.State, ArtifactState.Approved, "Reviewer"); await db.SaveChangesAsync(); return Results.Ok(new { artifact.Id, ETag \= Convert.ToBase64String(artifact.RowVersion) }); } catch (DbUpdateConcurrencyException) { return Results.Conflict(new { Message \= "Artifact modified by another process." }); } catch (InvalidArtifactTransitionException ex) { return Results.Problem(detail: ex.Message, statusCode: 409); } }).AddEndpointFilter\<IdempotencyFilter\>();

// 5\. Revoke Artifact (Admin Override) group.MapPut("/{id:guid}/revoke", async (Guid id, GovernanceDbContext db) \=\> { var artifact \= await db.Artifacts.FindAsync(id); if (artifact \== null) return Results.NotFound();

try { artifact.State \= ArtifactLifecycleManager.Transition(artifact.State, ArtifactState.Revoked, "Admin"); // Implement Outbox event for Cache Invalidation here await db.SaveChangesAsync(); return Results.Ok(); } catch (InvalidArtifactTransitionException ex) { return Results.Problem(detail: ex.Message, statusCode: 409); } }).RequireAuthorization("AdminPolicy").AddEndpointFilter\<IdempotencyFilter\>();

// 6\. Promote to Active Memory (System Workflow via Outbox) group.MapPost("/{id:guid}/promote", async (Guid id, GovernanceDbContext db) \=\> { using var transaction \= await db.Database.BeginTransactionAsync(); try { var artifact \= await db.Artifacts.FindAsync(id); if (artifact \== null) return Results.NotFound();

artifact.State \= ArtifactLifecycleManager.Transition(artifact.State, ArtifactState.Committing, "System");

var outboxMessage \= new OutboxMessage { EventType \= "ArtifactCommitted", Payload \= JsonSerializer.Serialize(new { artifact.Id, artifact.TenantId }) };

db.OutboxMessages.Add(outboxMessage); await db.SaveChangesAsync(); await transaction.CommitAsync();

return Results.Accepted(); } catch (Exception ex) { await transaction.RollbackAsync(); return Results.Problem(detail: "Promotion failed. Transaction rolled back.", statusCode: 500); } }); } }

/// \<summary\> /// Middleware filter to enforce HTTP idempotency using distributed caching. /// \</summary\> public class IdempotencyFilter : IEndpointFilter { private readonly IDistributedCache \_cache;

public IdempotencyFilter(IDistributedCache cache) { \_cache \= cache; }

public async ValueTask\<object?\> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next) { if (context.HttpContext.Request.Headers.TryGetValue("X-Idempotency-Key", out var key)) { var cachedResponse \= await \_cache.GetStringAsync(key); if (\!string.IsNullOrEmpty(cachedResponse)) { context.HttpContext.Response.Headers\["X-Idempotent-Response"\] \= "true"; return Results.Content(cachedResponse, "application/json"); }

var result \= await next(context);

// Cache successful state transition marker await \_cache.SetStringAsync(key, "Processed", new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow \= TimeSpan.FromHours(24) }); return result; } return Results.Problem("Missing X-Idempotency-Key header", statusCode: 400); } } }

7. Runtime Enforcement

Before an autonomous agent accesses an approved memory pattern, the Agent-Runtime Gateway intercepts the memory retrieval call. This component bridges the static memory storage and the dynamic context of the agent.

1. Evaluation & Caching: The gateway extracts the CEL falsification rules from the requested artifact and passes them to the IFalsificationEvaluator alongside the agent's current contextual state (e.g., available tools, security clearance). The result is cached locally on the gateway node with a short Time-To-Live (TTL) to prevent latency bottlenecks during tight reasoning loops10.

2. Cache Invalidation: If an administrator triggers the /revoke or /suspend APIs, the Outbox pattern dispatches a CacheInvalidationEvent, which actively flushes the relevant artifact IDs from all gateway nodes instantly.

3. Fail-Closed Default: If context data is missing (e.g., the target API state cannot be resolved), the CEL evaluator catches the resulting exception. The gateway enforces a fail-closed response, quarantining the memory pattern and forcing the agent to rely strictly on foundational policy generation, thereby mitigating hallucination spirals16.

4. Audit Sampling: To monitor the efficacy of falsification rules without overwhelming the telemetry pipeline, a randomized 1% subset of all evaluations (both passes and failures) are asynchronously published to an observability cluster2.

8. Review Interface Contract

The internal dashboard provided to safety engineers requires a deterministic data structure to accurately render the source graphs, target graphs, and the mathematical distances computed by the optimal transport solver4.

C\# namespace AgentGovernance.Contracts { using System.Collections.Generic;

/// \<summary\> /// Contract sent to the UI rendering engine for human review. /// \</summary\> public record GraphDashboardContract( string ArtifactId, GraphTopology SourceTopology, GraphTopology TargetTopology, IEnumerable\<MatchedNodePair\> MappedNodes, IEnumerable\<EditOperation\> ProposedEditOperations, FgwScoreMetrics AlignmentMetrics, IEnumerable\<FalsificationRuleView\> Rules, IEnumerable\<string\> ImpactedFleets );

public record GraphTopology(List\<string\> Nodes, List\<string\> Edges); public record MatchedNodePair(string SourceNode, string TargetNode, double TransportCost); public record EditOperation(string Type, string TargetNodeId, double Cost); public record FgwScoreMetrics(double FeatureCost, double StructuralCost, double TotalFgwDistance); public record FalsificationRuleView(string Expression, string Description); }

9. Tests

The integrity of the state machine and concurrency controls requires rigorous testing. The following xUnit test suite leverages Moq to validate the deterministic boundaries of the API and lifecycle management27.

C\# namespace AgentGovernance.Tests { using Xunit; using System; using AgentGovernance.StateMachine; using AgentGovernance.Data;

public class LifecycleTests { \[Fact\] public void Transition\_InvalidState\_ThrowsException() { // Arrange var currentState \= ArtifactState.Proposed;

// Act & Assert var exception \= Assert.Throws\<InvalidArtifactTransitionException\>(() \=\> ArtifactLifecycleManager.Transition(currentState, ArtifactState.Approved, "Reviewer") );

Assert.Contains("not permitted", exception.Message); }

\[Fact\] public void Transition\_ValidReviewerApproval\_ReturnsApproved() { // Arrange var currentState \= ArtifactState.UnderReview;

// Act var targetState \= ArtifactLifecycleManager.Transition(currentState, ArtifactState.Approved, "Reviewer");

// Assert Assert.Equal(ArtifactState.Approved, targetState); } }

public class FalsificationTests { \[Fact\] public async void Evaluate\_MissingVariable\_FailsClosed() { // Arrange var evaluator \= new AgentGovernance.Falsification.CelFalsificationEvaluator(); var context \= new AgentGovernance.Falsification.AgentRuntimeContext( TargetObject: "database\_cluster", AvailableTools: new System.Collections.Generic.List\<string\>(), // Missing specific tools ConfidenceThreshold: 0.9, SecurityClassification: 1, EnvironmentalState: new System.Collections.Generic.Dictionary\<string, object\>(), CurrentTimeUtc: DateTimeOffset.UtcNow );

// Act // Simulating an expression that requires a tool not present in the context, triggering an exception var result \= await evaluator.EvaluateAsync("context.environmentalState\['db\_status'\] \== 'active'", context);

// Assert Assert.True(result.IsFalsified); Assert.True(result.HasError); Assert.Contains("Evaluation Error", result.Reason); } } }

10. Diagrams

The following Mermaid diagrams illustrate the flow of data through the system, capturing the strict lifecycle state management and the atomic commit sequence via the Outbox pattern.

Lifecycle State Machine Diagram

Code snippet graph TD A\[Proposed\] \--\>|Automated Checks Pass| B(ReadyForReview) A \--\>|Validation Fails| X(ValidationFailed) B \--\>|Reviewer Claims| C(UnderReview) C \--\>|Requests Changes| D(ChangesRequested) C \--\>|Rejects| Y(Rejected) C \--\>|Approves| E(Approved) E \--\>|System Outbox Initiated| F(Committing) F \--\>|Event Dispatched| G(Committed) G \--\>|Admin Pauses| H(Suspended) H \--\>|Admin Restores| G G \--\>|System Overrides| I(Superseded) G \--\>|Admin Deletes| J(Revoked) H \--\>|Admin Deletes| J

Atomic Commit Sequence (Outbox Pattern)

Code snippet sequenceDiagram participant Worker as Background Worker participant API as Minimal API participant DB as SQL Server (EF Core) participant Bus as Message Broker

Worker-\>\>API: POST /api/artifacts/{id}/promote API-\>\>DB: Begin Transaction API-\>\>DB: Update State to 'Committing' API-\>\>DB: Insert OutboxMessage (ArtifactCommitted) API-\>\>DB: Commit Transaction DB--\>\>API: Success API--\>\>Worker: 202 Accepted

loop Polling Worker-\>\>DB: Query pending OutboxMessages DB--\>\>Worker: Return ArtifactCommitted event Worker-\>\>Bus: Publish Event to Agent Memory Bus Bus--\>\>Worker: ACK Worker-\>\>DB: Mark OutboxMessage as Processed end

11. Threat and Failure Analysis

The transition of transient threat models to persistent ones introduces complex architectural challenges3.

1. Memory Poisoning and Context Drift: An advanced attacker may interact with an agent over multiple discrete sessions, introducing subtle logic errors or state alterations. If the offline alignment process categorizes these interactions as a "successful generalized pattern," the malicious logic could be codified2. The primary mitigation relies on the human review gate analyzing the provenance topology and identifying anomalous feature distances, combined with strict falsification bounds that quarantine the payload when executed outside the attacker's localized context16.

2. Race Conditions During Human Review: Two safety engineers might attempt to review and approve the same artifact simultaneously, leading to conflicting approvals or overwritten modification requests. The EF Core optimistic concurrency implementation (RowVersion) ensures that the second commit fails instantly, triggering a 412 Precondition Failed response based on the mismatched ETag11.

3. Falsification Execution Denial of Service (DoS): If an overly complex or recursive falsification condition is injected into the artifact, it could cause CPU spikes across the agent runtime gateways during evaluation. The strict adoption of CEL prevents this threat by mathematically guaranteeing bounded evaluation times ([Figure omitted from source export]) and enforcing non-Turing completeness, preventing infinite loops9.

12. Unresolved Governance Questions

While this architecture enforces a deterministic boundary around agent memory, several long-term governance issues remain unresolved. First, Cross-Fleet Semantic Compatibility requires deeper mathematical analysis. Fused Gromov-Wasserstein alignment is adept at matching graph structures independently of exact vocabulary4. However, it remains statistically uncertain how to guarantee that a structural correction inferred from a low-risk IT operations fleet is semantically safe to inject into a high-risk financial compliance fleet without triggering a massive, manual re-validation effort2. Second, the system faces the threat of Falsification Rule Rot. As target APIs, infrastructure schemas, and environmental parameters naturally evolve, static CEL rules written during the human review phase will gradually become obsolete. An automated mechanism is needed to flag aging falsification criteria and prompt a re-review before valid patterns are erroneously quarantined by stale rules.

Works cited

1. What Is AI Agent Memory? | IBM, https://www.ibm.com/think/topics/ai-agent-memory

2. The Memory and State Management Pattern: Continuity Without AI Risk \- QAT Global, https://qat.com/memory-state-management-pattern-ai/

3. Guarding AI memory | Microsoft Security Blog, https://www.microsoft.com/en-us/security/blog/2026/06/22/guarding-ai-memory/

4. InfiGFusion: Graph-on-Logits Distillation via Efficient Gromov-Wasserstein for Model Fusion, https://arxiv.org/html/2505.13893v2

5. Fused Unbalanced Gromov–Wasserstein-Based Network Distributional Resilience Analysis for Critical Infrastructure Assessment \- MDPI, https://www.mdpi.com/2227-7390/14/3/417

6. Fused Gromov-Wasserstein Alignment for Graph Edit Distance Computation and Beyond \- VLDB Endowment, https://www.vldb.org/pvldb/vol18/p3641-tang.pdf

7. Convex Distance Operator Transport: A Convex and Geometry-Preserving Formulation \- arXiv, https://arxiv.org/html/2606.02047v1

8. Towards Pre-trained Graph Condensation via Optimal Transport \- NIPS, https://papers.nips.cc/paper\_files/paper/2025/file/aee5298251a418aad89618cf6b5e7ccc-Paper-Conference.pdf

9. CEL | Common Expression Language, https://cel.dev/

10. AI Human in the Loop: Production Oversight Patterns \- Redis, https://redis.io/blog/ai-human-in-the-loop/

11. Concurrency Handling with RowVersion in EF Core \- Medium, https://medium.com/@rohitsakhare/concurrency-handling-with-rowversion-in-ef-core-10fd0215d459

12. Use MassTransit To Implement OutBox Pattern with EF Core and MongoDB, https://antondevtips.com/blog/use-masstransit-to-implement-outbox-pattern-with-ef-core-and-mongodb

13. Implementing the Outbox Pattern in ASP.NET Core for Reliable Message Delivery, https://www.c-sharpcorner.com/article/implementing-the-outbox-pattern-in-asp-net-core-for-reliable-message-delivery/

14. Fused Gromov–Wasserstein Distance with Feature Selection \- arXiv, https://arxiv.org/html/2605.12161

15. What is human in the loop (HITL) in AI? Definition & examples | Decagon, https://decagon.ai/glossary/what-is-human-in-the-loop-hitl

16. AI Agents Need Memory Control Over More Context \- arXiv, https://arxiv.org/html/2601.11653v1

17. Graph Edit Distance as a Quadratic Assignment Problem \- ResearchGate, https://www.researchgate.net/publication/308956963\_Graph\_Edit\_Distance\_as\_a\_Quadratic\_Assignment\_Problem

18. Common Expression Language in Kubernetes, https://kubernetes.io/docs/reference/using-api/cel/

19. taspeotis/ExpressionEvaluator \- GitHub, https://github.com/taspeotis/ExpressionEvaluator

20. C\#-powered JavaScript Expression Evaluator \- Joel Holder's, https://joelholder.com/2012/04/04/c-string-javascript-expression-evaluator/

21. JsonLogic, https://jsonlogic.com/

22. JsonLogic Basics | json-everything, https://docs.json-everything.net/logic/basics/

23. c\# \- I need a fast runtime expression parser \- Stack Overflow, https://stackoverflow.com/questions/4392022/i-need-a-fast-runtime-expression-parser

24. mparlak/Flee: Fast Lightweight Expression Evaluator \- GitHub, https://github.com/mparlak/Flee

25. telus-labs/cel-net: Common Expression Library (CEL) .NET Implementation \- GitHub, https://github.com/telus-oss/cel-net

26. ICML Poster Position: Graph Matching Systems Deserve Better Benchmarks, https://icml.cc/virtual/2025/poster/40161

27. Optimistic Concurrency in EF Core 10: ASP.NET Core Web API Guide \- codewithmukesh, https://codewithmukesh.com/blog/concurrency-control-optimistic-locking-efcore/

28. Optimistic concurrency: IsConcurrencyToken and RowVersion \- Stack Overflow, https://stackoverflow.com/questions/31330015/optimistic-concurrency-isconcurrencytoken-and-rowversion

29. Implement the Transactional Outbox Pattern by Using Azure Cosmos DB \- Microsoft Learn, https://learn.microsoft.com/en-us/azure/architecture/databases/guide/transactional-out-box-cosmos

30. Transactional Outbox Pattern in .NET EF Core: Manual, and Semi-Auto \- Medium, https://jordansrowles.medium.com/outbox-pattern-in-net-ef-core-manual-and-semi-auto-e6bd2fd26a98

31. Implementing the Outbox Pattern with Kafka and C\# \- CODE Magazine, https://www.codemag.com/Article/2409071/Implementing-the-Outbox-Pattern-with-Kafka-and-C

32. How to Implement Idempotency Keys in .NET \- OneUptime, https://oneuptime.com/blog/post/2026-01-25-implement-idempotency-keys-dotnet/view

33. Idempotency in REST APIs in ASP.NET Core | by Daniel Alabuja | Medium, https://medium.com/@Alabuja/idempotency-in-rest-apis-in-asp-net-core-4a3f30cb8e94

34. Privacy-Preserved Evolutionary Graph Modeling via Gromov-Wasserstein Autoregression \- AAAI Publications, https://ojs.aaai.org/index.php/AAAI/article/view/26703/26475