Conventional Apps First
Built for standard .NET 10 and Java 27 backend services first. Foundgine requires no LLM, MCP server, GraphQL endpoint, or agent framework—those are optional consumer adapters.
Foundgine separates application meaning, persistence mapping, authorization, and physical execution from the APIs, workflows, and AI agents that consume them. Configure capabilities once with language-idiomatic fluent APIs, resolve operations against application-defined semantics, and execute deterministically through SQL, EF Core, or JPA—without making an API framework, ORM, database, or AI model the center of your architecture.
Callers describe intent. The semantic model defines meaning. Authorization determines authority. Planning defines logical execution. Providers define physical execution.
Built for standard .NET 10 and Java 27 backend services first. Foundgine requires no LLM, MCP server, GraphQL endpoint, or agent framework—those are optional consumer adapters.
Discovery, candidate retrieval, aliases, model output, and caller arguments are never permission. Every request binds to a host-owned SecurityExecutionContext and cryptographic warrant.
Keep existing EF Core DbContext, JPA EntityManager, PostgreSQL databases, Hot Chocolate, GraphQL Java, Redis, Keycloak, and Temporal infrastructure in place.
Foundgine is not an ORM, a GraphQL server, an AI agent framework, an identity/authorization server, a workflow engine, a database engine, or a generic SQL builder. Its sole purpose is the governed boundary between semantic intent and controlled provider execution.
Most applications implement the same business capability more than once: an API resolver applies one set of rules, a background worker applies another, an MCP tool adds its own checks, and an AI integration translates natural language into yet another execution path. Over time, validation, tenant scoping, field visibility, approval requirements, and persistence behavior drift. A secure endpoint does not make a second endpoint secure, and a prompt instruction is not an authorization policy.
Foundgine addresses that duplication by placing a semantic execution boundary between callers and data providers. The application defines what entities and operations mean, the host supplies trusted identity and policy, the runtime resolves and authorizes a request, and a provider executes the resulting constrained plan. GraphQL, MCP, application code, and workflow activities are consumers of that same boundary—not independent implementations of business authority.
Consumer interfaces translate requests; they do not become separate sources of business authority.
Identity is established by the hosting application or its trusted identity integration. Providers receive a constrained execution representation; they do not infer caller identity from user-supplied filters.
Owns business concepts, invariants, operation definitions, and the decision to expose a capability. Foundgine does not replace domain services or application workflows.
Names entities, fields, aliases, dimensions, relationships, and operation capabilities independently of physical tables and columns.
Resolves structured intent, applies bounded grounding, obtains authorization, creates a logical plan, and lowers it into provider-facing execution IR.
The host validates authentication and supplies trusted subject, tenant, claims, and policy decisions. Foundgine binds the authorized scope to execution.
Translate the provider-independent plan into supported SQL or ORM operations and enforce the provider contract. Physical execution remains separate from semantic meaning.
Temporal can coordinate durable steps, timers, retries, approvals, and compensation. Each activity obtains fresh authority and invokes Foundgine for the underlying operation.
The exact stages and their contracts are detailed in the canonical lifecycle reference. At a product level, a request moves through these boundaries in order; later stages cannot retroactively turn an untrusted input into authority.
The following excerpts use the Advanced Supply Chain sample's actual configuration style. Semantic configuration describes domain meaning and relationships; persistence configuration is separate. The full sample contains additional entities, mappings, policies, and registrations.
public sealed class SupplierModelConfiguration
: FoundgineModelConfiguration<Supplier>
{
public override void Configure(FoundgineModelBuilder<Supplier> model)
{
model.ToEntity("Supplier");
model.HasAlias("Vendor", 95);
model.HasAlias("Seller", 90);
model.HasMinimumWeight(80);
model.HasDimension(x => x.Country).As("country");
model.HasDimension(x => x.TenantId).As("tenant");
model.Property(x => x.Country).HasAlias("State", 85);
model.HasRelationship(x => x.Certifications)
.To<SupplierCertification>().Named("certifications");
model.HasRelationship(x => x.Incidents)
.To<ComplianceIncident>().Named("incidents");
}
}
static final class SupplierSemantics
extends FoundgineModelConfiguration<Supplier> {
@Override
public void configure(FoundgineModelBuilder<Supplier> model) {
model.toEntity("Supplier");
model.hasFieldNaming(FieldNaming.PASCAL_CASE);
model.hasAlias("Vendor", 95);
model.hasAlias("Seller", 90);
model.hasMinimumWeight(80);
model.hasDimension(Supplier::country).as("country");
model.hasDimension(Supplier::tenantId).as("tenant");
model.property(Supplier::country).hasAlias("State", 85);
model.hasMany("certifications", SupplierCertification.class);
model.hasMany("incidents", ComplianceIncident.class);
}
}
Both examples configure the same kinds of semantic facts while retaining idiomatic language APIs. The
Java sample registers these configurations through FoundgineModel and
FoundgineModelRegistrar; the C# sample registers configuration classes through its model
builder. See the
C# configuration source
and
Java configuration source.
Read the security and warrant specification, mutation lifecycle, and audit and observability design for the detailed contracts and deployment requirements.
Retrieval is a bounded semantic-discovery aid, not an authority system. The runtime grounds candidates against configured entities, fields, aliases, relationships, and limits. If candidates remain ambiguous, the request requires clarification or is rejected rather than silently selecting a convenient interpretation.
Mutations follow a controlled lifecycle: propose a mutation, validate and dry-run the proposed plan, obtain the required approval against the exact proposal, then execute under fresh valid authority. The resulting execution receipt records the outcome and relevant provenance. Approval is not a substitute for rechecking authorization at execution time.
GraphQL adapters translate schema selections and mutation requests into Foundgine operations. Hot Chocolate remains the GraphQL server; Foundgine supplies the shared semantic and authorization boundary.
MCP exposes bounded tools for capability discovery and governed execution. Agent frameworks may choose tools and formulate intent, but neither prompts nor model output can mint authority.
Temporal owns durable orchestration. Foundgine owns authorization and execution of each business operation; workers should obtain fresh activity-scoped authority on every attempt.
See GraphQL, identity, and Temporal integrations, MCP and agent integration, and the agent clarification and execution walkthrough.
These components do not all have the same role. C# and Java contain server-side runtime and provider implementations. TypeScript, Python, and WebAssembly are thin transport clients: they call a running Foundgine server and do not embed the semantic runtime or enforce server-side authorization locally.
| Technology | Role in the repository | Implementation status / boundary |
|---|---|---|
| C# / .NET | Server runtime, semantic model, planning, authorization, providers and integrations | Implemented Main server-side implementation; see NuGet package and sample documentation. |
| Java | Server runtime, semantic model, planning, authorization, providers and integrations | Implemented Server-side implementation with Maven modules and Advanced Supply Chain sample. |
| EF Core | .NET ORM provider | Implemented Provider integration in the C# provider packages. |
| JPA / Hibernate | Java ORM provider | Implemented Java ORM provider path; validate the chosen dialect and feature set against provider conformance documentation. |
| TypeScript | MCP and Temporal HTTP client | Source implemented Thin client; requires a .NET or Java Foundgine host. |
| Python | Async and sync MCP / Temporal HTTP client | Source implemented Repository source and tests; README documents local editable installation and does not claim a PyPI release. |
| WebAssembly (Rust core) | Thin WASM transport client for MCP and Temporal HTTP | Source implemented Build from the repository with the documented Rust / wasm-bindgen toolchain; not a server runtime. |
Package publication and runtime capability are separate questions. Consult the package and module directory and each SDK's README before assuming that a source project is published to a public registry or that a client SDK contains server functionality.
A typical deployment runs a Foundgine-enabled application service beside its database and optional shared infrastructure. The host validates incoming credentials, builds the trusted security context, registers the semantic model and provider, and exposes only the interfaces required by the application. MCP and GraphQL can be hosted by the same service or separate adapters; Temporal workers are commonly deployed separately from the HTTP API. Redis-backed replay/session controls, durable audit, event stores, and outbox dispatchers are optional infrastructure selected according to the guarantees the deployment requires.
Start with the reference samples, deployment topologies, production operations guide, and developer onboarding.
Every entry surface—typed C#/Java code, dynamic queries, JSON intent, Hot Chocolate GraphQL, GraphQL Java, MCP tools, Microsoft Agent Framework, LangChain4j, Spring Boot, or Temporal activities—converges on one monotonic pipeline before any provider work occurs.
The canonical security object for reads (and SemanticMutationOperationGraph for writes). Logical traversals (e.g., Customer.transactions) are expanded into intermediate entities and edges before authorization runs so shortcuts cannot tunnel past denied entities.
SemanticPlan carries an immutable SemanticPlanAuthorizationBinding recording the exact frozen semantic contract fingerprint and authorization decision fingerprint. Planner rewrites must preserve the binding; tampering or drift fails closed.
ExecutionIRCompiler refuses unbound plans. The final execution gate requires a provider security proof bound to the exact provider plan and exact ExecutionIR, then emits immutable ExecutionEvidence and ExecutionReceipt records.
Each stage in Foundgine's monotonic pipeline consumes an immutable artifact from the preceding stage and produces a cryptographically verifiable artifact for the next stage. No provider or adapter can jump ahead or mutate an upstream artifact without invalidating downstream fingerprints.
| Stage | Component (.NET / Java) | Artifact Produced | Fail-Closed Invariant |
|---|---|---|---|
| 01–02. Intent | SemanticQuery, GraphQL/MCP/JSON adapters |
SemanticOperation / SemanticMutationIntent |
Rejects malformed syntax, unknown operators, or structural limit violations before resolution. |
| 03–04. Graph | SemanticOperationGraphBuilder |
SemanticOperationGraph |
Expands logical traversal shortcuts (e.g., Customer.transactions) into all intermediate entities and FK edges so hidden hops are explicitly authorized. |
| 05–06. Grounding | SemanticLexicalResolver |
GroundingDecision (Committed) |
If free-form vocabulary maps to ≥2 distinct semantic signatures or falls below minimumAliasWeight, returns RequiresClarification with Committed = null. |
| 07. Authority | ISemanticAuthorizationPolicy + Warrant Verifier |
AuthorizationDecision + Row Predicates |
Evaluates host-owned SecurityExecutionContext, warrant signature, delegation chain, and revocation epoch; injects row-level predicates; denies empty field projections. |
| 08. Plan Bind | SemanticPlanner |
SemanticPlan + SemanticPlanAuthorizationBinding |
Binds logical plan to frozen MetadataRegistry SHA-256 fingerprint and authorization decision digest; optimizer rewrites must preserve binding identity. |
| 09. Lowering | ExecutionIRCompiler |
ExecutionIR (Scans, Joins, Predicates, Sorts) |
Refuses unbound or tampered plans; lowers authorization expressions into parameterized relational/ORM filter trees with deterministic tie-breaker keys. |
| 10–11. Dispatch | SqlExecutionProvider / FoundgineEfReader / JpaOrmProvider |
Provider Security Proof + Materialized Rows | Provider gate verifies proof against exact ExecutionIR; plan cache keys include full authorization predicate fingerprint; consumes single-use replay nonce on writes. |
| 12. Evidence | BufferedDurableAuditLog / ExecutionReceipt |
ExecutionEvidence & Signed Receipt |
Records principal, tenant, warrant ID, contract fingerprint, plan fingerprint, row counts, and timestamps into lossless durable audit storage. |
Foundgine's primary authoring surface is a five-concern fluent configuration model (FoundgineModel) that keeps domain classes free of persistence attributes and compiles to the exact same MetadataRegistry as build-time AOT generators. Calling Build() / build() validates the entire model in one pass and reports every missing key, unmapped relationship, or type mismatch in a single exception.
| Configuration Concern | .NET 10 Base Class | Java 27 Base Class | Responsibility |
|---|---|---|---|
| Semantic Entity & Aliases | FoundgineModelConfiguration<TModel> |
FoundgineModelConfiguration<TModel> |
Business identity, fields, weighted aliases, dimensions, logical traversals. |
| Persistence Table & Columns | FoundginePersistenceConfiguration<TEntity> |
FoundginePersistenceConfiguration<TEntity> |
Physical table/schema name, column mappings, primary key, indexes, constraints. |
| Model-to-Storage Map | FoundgineEntityMap<TModel, TEntity> |
FoundgineEntityMap<TModel, TEntity> |
Maps semantic members to storage members (or FoundgineIdentityEntityMap<T> / Convention()). |
| Relationship Foreign Keys | FoundgineConnectionConfiguration |
FoundgineConnectionConfiguration |
Binds semantic relationships to physical foreign keys (HasForeignKey / HasForeignKeyOnSource). |
| Model Connections & Predicates | FoundgineModelConnectionConfiguration<TModel> |
FoundgineModelConnectionConfiguration<TModel> |
Cross-entity visits, explicit conversions, and authorization expressions. |
using Foundgine.Core.Semantic.Configuration;
using Foundgine.Core.Semantic.Metadata;
public sealed class SupplyChainModel : FoundgineModel
{
public override void Configure(FoundgineModelBuilder model)
{
model.Configure<CustomerSemantics>();
model.Configure<OrderSemantics>();
model.Configure<OrderLineSemantics>();
model.Configure<CustomerTable>();
model.Configure<OrderTable>();
model.Configure<FoundgineIdentityEntityMap<Customer>>();
model.Configure<FoundgineIdentityEntityMap<SalesOrder>>();
model.Configure<SupplyChainConnections>();
}
}
internal sealed class CustomerSemantics : FoundgineModelConfiguration<Customer>
{
public override void Configure(FoundgineEntityConfigurationBuilder<Customer> e)
{
e.Alias("Client", weight: 90);
e.Property(x => x.Name).Alias("CustomerName", weight: 85);
}
}
internal sealed class OrderTable : FoundginePersistenceConfiguration<SalesOrder>
{
public override void Configure(FoundginePersistenceBuilder<SalesOrder> m)
{
m.ToTable("tbl_order").HasKey(x => x.Id);
m.Property(x => x.Id).HasColumnName("ord_id");
m.Property(x => x.CustomerId).HasColumnName("cust_id");
m.Property(x => x.Total).HasColumnName("ord_total");
}
}
internal sealed class SupplyChainConnections : FoundgineConnectionConfiguration
{
public override void Configure(FoundgineConnectionBuilder connections)
{
connections.HasRelationship<Customer, SalesOrder>()
.Using<Customer, SalesOrder>()
.HasForeignKey(o => o.CustomerId)
.References(c => c.Id);
}
}
MetadataRegistry registry = new SupplyChainModel().Build();
import com.foundgine.core.semantic.configuration.*;
import com.foundgine.core.semantic.metadata.MetadataRegistry;
public final class ErpModel extends FoundgineModel {
@Override
public void configure(FoundgineModelRegistrar model) {
model.configure(CustomerSemantics.class);
model.configure(CustomerStorage.class);
model.configure(CustomerMap.class);
model.configure(CustomerOrderConnections.class);
}
}
public final class CustomerOrderConnections extends FoundgineModelConnectionConfiguration<Customer> {
@Override
public void configure(FoundgineModelConnectionBuilder<Customer> connections) {
connections.hasConnection(CustomerErp.class, Customer::customer)
.maps(Customer::customerId, CustomerErp::id)
.authorize(UserContext.class, "SameTenant", a ->
a.context(UserContext::tenantId)
.eq(a.resource(CustomerErp::tenantId)));
}
}
MetadataRegistry registry = new ErpModel().build();
// 1. Typed Query (compile-time checked)
var typedResult = await foundgine
.Query<Customer>()
.Select(c => new { c.Id, c.Name })
.Where(c => c.TenantId == tenantId)
.Take(50)
.ExecuteAsync(ct);
// 2. Dynamic Query (runtime string names)
var dynamicResult = await foundgine
.Query("Customer")
.Select("Id", "Name")
.WhereRelated("transactions",
SemanticRelationshipQuantifier.Some,
tx => tx.Where("Amount", SemanticFilterOperator.Gt, 100))
.ExecuteAsync(ct);
// 3. Parity-Verified SemanticQuery Builder
var op = SemanticQuery.From(metadata, "Warehouse")
.Select("Id", "Name")
.WhereEq("Region", "NZ")
.Include(warehouseLots, lots => lots
.Select("Sku", "OnHand")
.WhereNeq("OnHand", 0)
.OrderBy("Sku", SemanticSortDirection.Asc)
.Take(50))
.Build();
// Held to shared vectors in src/conformance/semantic-query-vectors.json
var op = SemanticQuery.from(metadata, "Warehouse")
.select("Id", "Name")
.whereEq("Region", "NZ")
.include(warehouseLots, lots -> lots
.select("Sku", "OnHand")
.whereNeq("OnHand", 0)
.orderBy("Sku", SemanticSortDirection.ASC)
.take(50))
.build();
// Execute via IFoundgineExecutor
ExecutionResult result = executor.executeAsync(request, securityContext).join();
// Startup composition: inject IFoundgineExecutor in application services
services.AddFoundgine(options =>
{
options
.UseMetadata(new SupplyChainModel().Build())
.ConfigureSemantics(model =>
{
// Logical traversal expanded before authorization checks intermediate nodes
model.Traversal(
"Customer",
"transactions",
"customerRelationships",
"contract",
"transactions");
})
.ConfigureAuthorization(auth =>
{
// Application-supplied semantic policy
});
});
Calling new MyModel().Build() (.NET) or new MyModel().build() (Java) runs deterministic graph checks before returning a frozen MetadataRegistry:
HasKey) and resolve all mapped columns.All filter trees lower identically across ADO.NET SQL, EF Core, JPA Criteria, and InMemory providers:
To prevent skipped or duplicated rows during cursor pagination across distributed replicas:
ExecutionIRCompiler automatically appends the entity primary key as a final deterministic tie-breaker sort column if not already present.MaxCursorLength = 4,096 bytes.Writes are explicitly opt-in and follow a deterministic multi-stage lifecycle separate from reads. Mutation authorization verifies entity write permission, field write permission for supplied values, field read permission for returned fields, and read permission for any fields/relationships referenced in mutation filters.
// Compose a multi-step order + lines + shipment mutation graph
var graph = new SemanticMutationIntentBuilder(model)
.Create("PurchaseOrder", "order")
.Set("SupplierId", supplierId)
.Return("Id")
.Create("PurchaseOrderLine", "line")
.SetFrom("PurchaseOrderId", "order", "Id") // binds generated parent PK
.Set("ProductId", productId)
.Set("Quantity", 25m)
.Return("Id", "PurchaseOrderId")
.Create("Shipment", "shipment")
.SetFrom("PurchaseOrderId", "order", "Id")
.Set("Quantity", 25m)
.Return("Id")
.Build();
// 1. Dry-run validates & computes deterministic plan fingerprint
DryRunResult dryRun = await mutations.DryRunAsync(graph, securityContext, ct);
// 2. Host governance approves the exact plan fingerprint
PlanApproval approval = await mutations.ApproveAsync(dryRun.PlanFingerprint, approverContext, ct);
// 3. Execution re-verifies warrant, revocation, approval & plan binding before SQL/ORM write
MutationExecutionResult result = await mutations.ExecuteApprovedAsync(approval, securityContext, ct);
PlanFingerprint.
Free-form language is resolved through SemanticLexicalResolver.Ground(...) (.NET) and SemanticLexicalResolver.ground(...) (Java). Approximate retrieval providers (ElasticsearchSemanticLexicalCandidateSource or PgVectorSemanticLexicalCandidateSource) only propose vocabulary candidates; the semantic graph validates structural legality and groups paths by semantic signature.
When SemanticLexicalResolver.Ground(...) receives a natural-language phrase, it executes five deterministic, bounded phases before emitting a GroundingDecision:
MaxTokens = 32 and cooperative cancellation.ISemanticLexicalCandidateSource providers (Elasticsearch BM25 or PostgreSQL pgvector) within RetrievalTimeout = 2s for matching entity names, field names, and weighted aliases.MetadataRegistry connecting candidate entities and predicates, halting immediately if explored paths exceed MaxPathsExplored = 5,000 or Timeout = 250ms (GroundingOutcome.BudgetExceeded)."client" and "customer") that collapse to the same semantic signature reinforce one another rather than causing false ambiguity.minimumAliasWeight, the resolver fails closed with GroundingOutcome.RequiresClarification and populates CompetingInterpretations.GroundingOutcome |
When It Occurs | Committed |
Execution Behavior |
|---|---|---|---|
| Committed | Exactly one semantic meaning dominates, or multiple candidates collapse onto the same signature and satisfy minimumAliasWeight. |
Populated | Proceeds to authorization, plan binding, and execution. |
| RequiresClarification | Two or more distinct semantic meanings remain in contention (e.g., "active customers" → AccountEnabled vs. HasRecentOrder), or alias evidence falls below threshold. |
null |
Refuses to guess; exposes CompetingInterpretations for sanitized clarification. |
| Unresolved | No legal semantic path exists or a token has no declared vocabulary (e.g., unmodeled threshold "big" or relative date "last summer"). |
null |
Fails closed; names the exact unresolved token in Reason. |
| BudgetExceeded | Any bounded search control fires (MaxTokens=32, MaxPathsExplored=5000, Timeout=250ms, RetrievalTimeout=2s, or Cancelled). |
null |
Fails closed with BudgetLimit; partial cutoff candidates are diagnostic-only. |
// Declare vocabulary evidence weights (1..100) without granting authority
[FoundgineAlias("Vendor", Weight = 95)]
[FoundgineAlias("Seller", Weight = 90)]
public sealed record Supplier(
Guid Id,
[property: FoundgineAlias("State", Weight = 85)] string Country);
// Enforce minimum alias evidence threshold before committing
var resolver = new SemanticLexicalResolver(
contract,
candidateSource,
minimumAliasWeight: 80);
GroundingDecision decision = resolver.Ground("active customers");
switch (decision.Outcome)
{
case GroundingOutcome.Committed:
// Safe to proceed to authorization & planning
break;
case GroundingOutcome.RequiresClarification:
// Surface sanitized options from decision.CompetingInterpretations
break;
case GroundingOutcome.Unresolved:
case GroundingOutcome.BudgetExceeded:
// Fail closed; inspect decision.Reason / decision.BudgetLimit
break;
}
ISemanticLexicalCandidateSource): Implemented interchangeably by ElasticsearchSemanticLexicalCandidateSource (BM25/fuzzy) and PgVectorSemanticLexicalCandidateSource (cosine/L2/inner-product vector search). Resolves words like "nike" or "shoes" to schema entities, fields, and relationships.IApproximateCandidateSource): Implemented by PostgresRetrievalCandidateSource in .NET and Java behind RetrievalStrategy:
Fuzzy — PostgreSQL pg_trgm trigram similarityFullText — native tsvector / websearch_to_tsquerySearch — optional ParadeDB pg_search BM25GraphSimilarity — optional Apache AGE Cypher neighbor traversalFoundgine enforces defense-in-depth across every transport, planner, cache, and storage provider:
Identity, tenant, audience, and roles come exclusively from the host's ISecurityExecutionContextProvider. Delegated warrants require an explicit trusted root issuer, a complete root-to-leaf chain on SecurityExecutionContext, and a configured ISecurityWarrantDelegationTrustResolver verifying every signature and ensuring child authority never exceeds parent authority.
Conditional access policies emit provider-independent predicates (e.g., resource.TenantId == context.TenantId) that travel inside the logical plan and are lowered into parameterized SQL WHERE clauses or ORM filters. An empty authorized field set fails closed rather than widening to SELECT *.
Provider plan caching reuses compiled physical shapes keyed by the full plan fingerprint—including authorization predicates—while binding context parameters at execution time. Cache hits never skip semantic resolution or authorization revalidation.
Horizontally scaled hosts use RedisSecurityWarrantReplayStore and RedisSecurityWarrantRevocationStore (Redis/Valkey/Garnet) wrapped in AnchoredSecurityWarrantRevocationStore backed by PostgreSQL GREATEST epoch anchors. If Redis lags behind the durable anchor or is unreachable, warrant authorization fails closed.
// 1. Provider-independent conditional predicate (lowered to SQL WHERE / ORM predicate)
Expression<Func<UserContext, Employee, bool>> CanReadEmployee =>
(user, employee) => user.TenantId == employee.TenantId;
// 2. Distributed Redis/Valkey/Garnet replay + monotonic revocation anchored in PostgreSQL
var mux = await ConnectionMultiplexer.ConnectAsync("redis:6379,syncTimeout=1000");
var redisRevocation = new RedisSecurityWarrantRevocationStore(new StackExchangeScriptBackend(mux));
var pgAnchor = new PostgresSecurityWarrantRevocationEpochAnchor(pgDataSource);
builder.Services.AddFoundgine(o =>
{
o.WarrantReplayStore = new RedisSecurityWarrantReplayStore(new StackExchangeReplayBackend(mux));
});
builder.Services.AddSingleton<ISecurityWarrantRevocationStore>(
new AnchoredSecurityWarrantRevocationStore(redisRevocation, pgAnchor));
SecurityResourceLimits)| Guard | Default Max | Guard | Default Max | Guard | Default Max |
|---|---|---|---|---|---|
| Selection depth | 32 | Operation-graph nodes | 256 | Page size | 1,000 |
| Selection nodes | 256 | Operation-graph fields | 512 | Offset | 1,000,000 |
| Filter depth / nodes | 32 / 256 | Operation-graph edges | 255 | Mutation ops / batch | 128 |
| Order terms / path depth | 64 / 16 | Cursor length | 4,096 | Mutation fields / effects | 64 / 256 |
Host-minted warrants cryptographically bind execution authority to a specific runtime context:
When an orchestrator or agent delegates authority to a sub-agent (SecurityExecutionContext.DelegationChain):
ISecurityWarrantDelegationTrustResolver.Exact runtime behavior when infrastructure or tokens degrade:
Foundgine's ORM providers sit on top of a provider-neutral core (Foundgine.Providers.Orm in .NET, storage/orm in Java) that translates authorized ExecutionIR into typed EF Core IQueryable or JPA Criteria queries—enforcing root and child permission filters inside SQL, binding all values as parameters, and guaranteeing deterministic tie-breaker ordering for cursor pagination.
// One-line EF Core registration
services.AddFoundgineEf(
new SupplyChainModel().Build(),
(sp, o) => o.UseNpgsql(connectionString));
// Authorized semantic read via FoundgineEfReader
var result = await reader.ReadAsync(SalesOrder.Entity, q => q
.Where(SalesOrder.Id.Eq(orderId), SalesOrder.CustomerId.Eq(customerId))
.Include(SalesOrder.Relationships.Lines), ct);
// Mechanical generic CRUD repository (check capability first for writes)
var repo = sp.GetRequiredService<IFoundgineRepository<Shipment>>();
await repo.UpdateAsync(id, x => x.Status, "Delivered");
// Name-addressed JPA gateway with mandatory ReadGate authorization
var entities = new JpaEntities(entityManager, registry, readGate);
var warehouse = entities.entity("Warehouse");
var rows = warehouse.read(Map.of("Region", "NZ"), List.of("Id", "Name"));
// Java schema diff & Flyway SQL generator (foundgine-migrations)
// mvn exec:java -Dexec.mainClass=com.foundgine.migrations.MigrationsCli ...
// Commands:
// migrations add InitialCreate
// migrations has-pending-model-changes
// migrations script
// database update
Between logical planning (SemanticPlan) and physical database execution, ExecutionIRCompiler lowers every authorized operation into a closed, immutable relational/graph algebra (ExecutionIR). Storage providers translate ExecutionIR nodes mechanically without re-interpreting high-level semantic intent:
TenantId, SubjectId, cursor keys) binds as a positional/named ADO.NET or JDBC parameter.SHA256(ContractFP + PlanBindingFP + Dialect), guaranteeing two roles with different row predicates never collide in cache.using Foundgine.Core.Security;
using Foundgine.Runtime.Authorization;
public sealed class SupplyChainAuthorizationPolicy : ISemanticAuthorizationPolicy
{
public ValueTask<SemanticAuthorizationDecision> AuthorizeAsync(
SemanticAuthorizationRequest request,
CancellationToken ct)
{
var ctx = request.SecurityContext;
if (!ctx.IsAuthenticated)
return ValueTask.FromResult(SemanticAuthorizationDecision.Deny("Unauthenticated caller."));
// 1. Enforce mandatory tenant row-level predicate lowered into SQL WHERE / EF IQueryable
var tenantPredicate = SemanticFilter.Eq("TenantId", ctx.TenantId);
// 2. Restrict sensitive fields unless caller holds 'finance' role
var allowedFields = request.RequestedFields
.Where(f => f != "UnitCost" || ctx.Roles.Contains("finance"))
.ToArray();
if (allowedFields.Length == 0)
return ValueTask.FromResult(SemanticAuthorizationDecision.Deny("No authorized fields remain."));
return ValueTask.FromResult(
SemanticAuthorizationDecision.Allow(allowedFields, tenantPredicate));
}
}
import com.foundgine.core.security.*;
import com.foundgine.runtime.authorization.*;
public final class ErpAuthorizationPolicy implements SemanticAuthorizationPolicy {
@Override
public SemanticAuthorizationDecision authorize(SemanticAuthorizationRequest request) {
var ctx = request.securityContext();
if (!ctx.isAuthenticated()) {
return SemanticAuthorizationDecision.deny("Unauthenticated caller.");
}
var tenantPredicate = SemanticFilter.eq("TenantId", ctx.tenantId());
var allowedFields = request.requestedFields().stream()
.filter(f -> !f.equals("UnitCost") || ctx.roles().contains("finance"))
.toList();
if (allowedFields.isEmpty()) {
return SemanticAuthorizationDecision.deny("No authorized fields remain.");
}
return SemanticAuthorizationDecision.allow(allowedFields, tenantPredicate);
}
}
Foundgine.Providers.Aot.Generator (Roslyn incremental source generator) and Foundgine.Providers.Orm.Generator emit reflection-free metadata and EF maps at compile time. In Java, foundgine-aot-generator (FoundgineAotProcessor) processes @FoundgineModel and @FoundgineModelEntityMap annotations to emit GeneratedFoundgineMetadata.build().
// C# (.NET 10) — Processed at build time by Foundgine.Providers.Aot.Generator
[FoundgineEntity("SalesOrder", Schema = "erp", Table = "tbl_order")]
public sealed record SalesOrderModel(
[property: FoundgineKey, FoundgineColumn("ord_id")] Guid Id,
[property: FoundgineColumn("cust_id")] Guid CustomerId,
[property: FoundgineColumn("ord_total"), FoundgineAlias("OrderAmount", Weight = 90)] decimal Total);
// Emits reflection-free GeneratedFoundgineMetadata.Create() at compile time (Native AOT ready).
// Java 27 — Processed by com.foundgine.aot.FoundgineAotProcessor
// @FoundgineModel(name = "SalesOrder", table = "tbl_order")
// Generates GeneratedFoundgineMetadata.build() with zero runtime classpath scanning.
Extensions connect external API, identity, and orchestration frameworks to Foundgine's semantic boundary. They translate protocols and host contexts—they never duplicate authorization logic.
using Foundgine.Extensions.GraphQL.Http;
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
// Fail-closed POST /graphql: unlisted roots are forbidden; identity comes from JWT only
app.MapFoundgineGraphQL(o =>
{
o.QueryRootRoles["order"] = ["manager", "customer"];
o.QueryRootRoles["orderLine"] = ["manager"]; // customers reach lines only via their orders
o.Authorize = ctx =>
ctx.User.IsInRole("customer") && !int.TryParse(ctx.User.FindFirst("customer_id")?.Value, out _)
? new GraphQLAdapterError("FORBIDDEN", "A customer_id claim is required.", Category: "FORBIDDEN")
: null;
});
app.Run();
KeycloakSecurityExecutionContextProvider (.NET) and com.foundgine.extensions.keycloak (Java).FoundgineWarrantIssuer backed by KMS/HSM or mounted signing keys, with shared replay protection across replicas.PostgresOutbox records events in the same transaction as business writes; FoundgineTemporalOutboxPublisher dispatches workflow starts/signals; Temporal owns timers, retries, approvals, and compensations; each activity re-mints fresh host security context before invoking Foundgine./foundgine/workflows (processes, describe, start, status, decide, cancel) consumed directly by the TypeScript, Python, and WebAssembly SDKs.
Foundgine exposes six bounded tools over MCP Streamable HTTP (default POST /mcp, protocol version 2025-06-18, optional Mcp-Session-Id and replayable SSE). Write approvals use RSA-2048+ PKCS#1 v1.5 SHA-256 signed tokens (fgmcp1.<payload>.<sig>) bound to the exact plan fingerprint.
| MCP Tool | Purpose | Authority & Verification Rule |
|---|---|---|
foundgine_capabilities |
Discover entities, fields, relationships, and access levels visible to the caller. | Advisory only; never grants permission to execute. |
foundgine_query |
Execute natural-language or open read intent via lexical grounding. | Refuses ambiguous intent (RequiresClarification); enforces row/field predicates. |
foundgine_query_semantic |
Execute structured JSON read intent (rootEntity, selections, filter, order). |
Deterministic plan binding and cryptographic execution receipt. |
foundgine_mutation_dry_run |
Validate and authorize a mutation without committing side effects. | Returns canonical planFingerprint and previewed effects. |
foundgine_mutation_approve |
Issue an fgmcp1 signed approval token bound to an authorized mutation plan. |
Host-controlled governance; models have no approve tool in MAF. |
foundgine_mutation_execute_approved |
Execute a previously approved mutation plan. | Verifies signature, replay nonce, expiry, plan digest, and re-authorizes before write. |
using Foundgine.Providers.AgentFramework.Hosting;
using Microsoft.Agents.AI;
builder.Services.AddFoundgine(/* semantic model, providers */);
builder.Services.AddSingleton<ISecurityExecutionContextProvider, HttpContextSecurityProvider>();
builder.Services.AddSingleton<IChatClient>(/* any Microsoft.Extensions.AI chat client */);
builder.Services.AddFoundgineAgentFramework(o =>
{
o.AgentName = "orders";
o.EnableMutations = true; // wraps foundgine_mutation_execute in ApprovalRequiredAIFunction; no model approve tool
});
var agent = scope.ServiceProvider.GetRequiredKeyedService<AIAgent>("orders");
var session = await agent.CreateSessionAsync();
var response = await agent.RunAsync("Which purchase orders are overdue?", session);
// 1. LangChain4j AiServices integration (io.github.cristianbarragan:foundgine-providers)
FoundgineMcpServer server = FoundgineMcpServer.builder()
.serverInfo("foundgine", "3.4.2")
.withReadTools(tools)
.build();
Assistant assistant = AiServices.builder(Assistant.class)
.chatModel(model)
.tools(FoundgineLangChain4jTools.toolMap(server))
.build();
// 2. Spring Boot application.properties (off by default; protect /mcp with Spring Security)
// foundgine.mcp.enabled=true
// foundgine.mcp.path=/mcp
// foundgine.mcp.allowed-origins=https://app.example
import { FoundgineClient } from "@foundgine/typescript";
const client = new FoundgineClient({
baseUrl: "https://your-host.example",
token: async () => process.env.FOUNDGINE_TOKEN!,
});
try {
const contract = await client.execute("foundgine_capabilities", {});
const rows = await client.execute("foundgine_query_semantic", {
intentJson: JSON.stringify({
rootEntity: "Customer",
selections: [{ field: "Name" }],
limit: 20,
}),
});
console.log(contract.content, rows.content, rows.isError);
} finally {
await client.close();
}
import asyncio, json
from foundgine import FoundgineClient
async def main() -> None:
async with FoundgineClient("https://your-host.example", token=lambda: "tok") as client:
rows = await client.execute(
"foundgine_query_semantic",
{"intentJson": json.dumps({"rootEntity": "Customer", "selections": [{"field": "Name"}], "limit": 20})},
)
print(rows.content, rows.is_error)
asyncio.run(main())
import { FoundgineClient, init } from "@foundgine/wasm";
await init(); // load .wasm once in Browser, Cloudflare Worker, Deno, or Node 20+
const client = new FoundgineClient({
baseUrl: "https://your-host.example",
token: async () => "tok",
fetch,
});
const rows = await client.execute("foundgine_query_semantic", {
intentJson: JSON.stringify({ rootEntity: "Customer", selections: [{ field: "Name" }], limit: 20 }),
});
Complete directory map of Foundgine/Foundgine (v3.4.2) annotated with the canonical XML documentation (<summary>) and Javadoc descriptions from each assembly, package, and primary class/interface. Use the filter bar below to search by class name, namespace, file path, or responsibility.
Foundgine.sln): Core, Runtime, Providers, Extensions, and runnable samples.
Root fluent model entry point. Aggregates entity semantic configurations, persistence table/column mappings, model-to-entity mappings, and relationship connections, validating the entire model in a single pass via Build() into an immutable MetadataRegistry.
Configures business-facing semantic identity, fields, dimensions, weighted vocabulary aliases (Alias(..., weight)), and logical traversal shortcuts for TModel without introducing persistence attributes.
Configures physical storage structure for TEntity: database schema, table name (ToTable), primary keys (HasKey), column names (HasColumnName), nullability, and storage constraints.
Explicitly maps semantic model properties to physical storage entity properties, keeping domain types decoupled from legacy database column layouts (paired with FoundgineIdentityEntityMap<T> when shapes match).
Binds semantic relationships between source and target entities to physical foreign-key columns (HasRelationship<TSource, TTarget>().Using<...>().HasForeignKey(...)).
Immutable, deterministic catalog of validated EntityMetadata, FieldMetadata, RelationshipMetadata, and persistence mappings with a canonical SHA-256 contract fingerprint.
Parity-verified fluent read builder (SemanticQuery.From(metadata, root)) that constructs a canonical SemanticOperation with projections, predicates, sorting, pagination, and nested relationship includes.
Canonical security and planning unit for read operations. Expands logical traversal paths into explicit intermediate entity nodes and relationship edges so authorization evaluates every traversed hop.
Fluent builder for multi-step semantic writes (Create, Update, Delete) supporting cross-operation generated key bindings via SetFrom and compiling into a SemanticMutationOperationGraph.
Resolves free-form vocabulary expressions against the semantic model under strict token, path, and timeout budgets; returns GroundingDecision (Committed, RequiresClarification, Unresolved, or BudgetExceeded) and never guesses under ambiguity.
Non-authoritative vocabulary retrieval boundary used to propose candidate entities, fields, and aliases for lexical grounding without granting execution authority.
Transforms an authorized SemanticOperationGraph into a logical SemanticPlan carrying an immutable SemanticPlanAuthorizationBinding tied to the frozen contract and authorization decision fingerprints.
Compiles a bound SemanticPlan into provider-neutral ExecutionIR (scans, joins, lowered authorization row predicates, projections, sorts, and cursor bounds). Refuses unbound or tampered plans.
Immutable cryptographic provenance record attached to SemanticPlan capturing the frozen MetadataRegistry SHA-256 fingerprint, principal/tenant context digest, and authorization policy decision hash. Prevents plan-rewrite privilege escalation.
Provider-neutral intermediate representation encoding relational/graph scans, join topologies, injected row-level security predicates, authorized field projections, deterministic tie-breaker sorts, and pagination bounds.
Host-owned security envelope carrying authenticated principal identity, tenant ID, roles, scopes, optional cryptographic warrant, and root-to-leaf delegation chain.
Core storage provider Service Provider Interfaces accepting bound ExecutionIR trees and security proofs to materialize authorized read rows or transactional write receipts.
Algebraic intermediate representation nodes emitted by ExecutionIRCompiler separating logical query semantics from dialect SQL or ORM query translation.
Encapsulates policy allow/deny outcomes, allowed field projections, and provider-independent row-level predicate trees lowered into SQL WHERE or ORM filters.
Engine-enforced structural bounds guarding against query/mutation DoS (max selection depth 32, selection nodes 256, filter depth 32, graph nodes 256, page size 1,000, mutation batch 128).
Primary runtime entry point orchestrating the 12-stage canonical lifecycle: intent normalization, operation graph expansion, authorization, plan binding, ExecutionIR compilation, provider dispatch, and receipt emission.
Governs the multi-stage write pipeline (DryRunAsync, ApproveAsync, ExecuteApprovedAsync), enforcing cryptographic plan-fingerprint approval binding, single-use replay nonces, and pre/post revocation checks.
Host-implemented authorization policy evaluating entity, field, and relationship permissions and emitting provider-independent row-level filter predicates into the logical plan.
Combines low-latency distributed revocation checks (e.g., Redis) with a durable monotonic database epoch anchor (e.g., PostgreSQL GREATEST), failing closed if cache state lags or disconnects.
Bounded, lossless asynchronous audit writer persisting signed ExecutionReceipt and mutation approval evidence to durable storage with configurable fail-closed backpressure.
Registers ActivitySource("Foundgine") distributed tracing spans and runtime execution/security metrics with automatic PII and token redaction.
Transport-neutral execution and approval gateway supporting atomic approval commits, encrypted approval envelopes (AES-256-GCM), and outbox evidence.
Compiles authorized ExecutionIR into parameterized dialect SQL (PostgreSQL, SQLite, SQL Server) with deterministic tie-breaker pagination, plan-cache fingerprint isolation, and batched transactional writes.
Dialect-specific SQL emitters translating canonical ExecutionIR nodes into parameterized PostgreSQL, SQLite, or T-SQL statements with dialect-native pagination, identifier quoting, and batching.
Manages multi-kid asymmetric public key sets for zero-downtime warrant rotation and versioned AES-256-GCM symmetric key rings with tenant/plan AAD binding.
Mints and verifies asymmetric-signed cryptographic warrants (iss, aud, sub, tid, jti, rev_seq, contract_fp) and validates root-to-leaf delegation attenuation chains.
Translates authorized ExecutionIR onto an existing EF Core DbContext via IQueryable projections and mandatory root/child permission predicates, preserving entity mappings and value converters.
Implements IApproximateCandidateSource for row-level candidate discovery across PostgreSQL pg_trgm fuzzy matching, native tsvector full-text search, optional ParadeDB pg_search BM25, and optional Apache AGE graph similarity.
Interchangeable vocabulary grounding candidate sources using Elasticsearch BM25/fuzzy queries or PostgreSQL pgvector similarity search over embedded semantic metadata.
Distributed Lua-scripted single-use warrant nonce replay prevention and monotonic revocation sequence store for Redis, Valkey, and Garnet clusters.
Implements MCP Streamable HTTP (2025-06-18) exposing the six bounded tools (foundgine_capabilities, foundgine_query, foundgine_query_semantic, and dry-run/approve/execute mutation tools) with RSA-2048+ fgmcp1 signed approval tokens.
Registers Microsoft Agent Framework (AIAgent) toolsets via AddFoundgineAgentFramework, wrapping write execution in ApprovalRequiredAIFunction while withholding approval issuance from the LLM.
Transactional event store, outbox dispatcher (FOR UPDATE SKIP LOCKED), and lossless durable audit log persisting signed ExecutionReceipt and mutation approval records alongside business transactions.
Deterministic in-process execution providers honoring the exact same ExecutionIR predicates, tie-breaker sorts, and transactional rollback semantics as SQL/EF Core for fast unit testing.
Roslyn incremental compile-time source generators emitting reflection-free MetadataRegistry builders and typed EF Core entity maps for Native AOT deployments.
Provides MapFoundgineGraphQL, mounting a fail-closed POST /graphql adapter with explicit QueryRootRoles allowlists, request-scoped JWT context extraction, and GraphQL error mapping.
Validates Keycloak OIDC/JWKS tokens and maps verified claims into a host-owned SecurityExecutionContext and short-lived cryptographic Foundgine warrant.
Bridges transactional PostgresOutbox events to Temporal workflows and exposes /foundgine/workflows control routes while re-minting fresh authority inside each Temporal activity.
Foundgine.Comparison, Foundgine.SupplyChain.Advanced, Foundgine.RedTeam, and AgentEndToEnd.
io.github.cristianbarragan) with full semantic, security, provider, extension, migration, and AOT parity.
com.foundgine.core — fluent model configuration, MetadataRegistry, SemanticQuery, lexical resolver, planner, ExecutionIR, and security models.
Java fluent model registrar and entity/persistence/connection configuration builders compiling to an immutable, fingerprinted MetadataRegistry via build().
Cross-language parity-verified fluent query builder (SemanticQuery.from(metadata, root)) producing canonical SemanticOperation trees.
Compiles authorized SemanticOperationGraph instances into bound SemanticPlan and provider-neutral ExecutionIR trees with automatic primary-key tie-breaker sorting.
Immutable Java 27 records carrying host-authenticated principal/tenant claims, cryptographic warrant delegation chains, and structural DoS resource limits.
Bounded lexical grounding engine (ground(...)) enforcing fail-closed ambiguity handling (GroundingOutcome.REQUIRES_CLARIFICATION) and token/path/timeout budgets.
com.foundgine.runtime — FoundgineEngine, mutation governance, warrant/delegation verification, and durable audit logging.
Java runtime orchestrator enforcing plan-binding verification, row-level predicate injection, warrant replay/revocation checks, and cryptographic execution receipts.
com.foundgine.providers — JDBC SQL, JPA ORM (JpaEntities, JpaOrmProvider), InMemory, Redis, MCP server, LangChain4j, Spring Boot AutoConfig, and retrieval providers.
Translates authorized ExecutionIR into JPA Criteria queries against an existing EntityManager with mandatory ReadGate authorization checks.
Compiles authorized ExecutionIR into parameterized JDBC SQL queries and batched transactional mutations with deterministic tie-breaker sorting and fingerprint-keyed plan caching.
Java implementation of IApproximateCandidateSource supporting PostgreSQL pg_trgm trigram similarity, tsvector full-text search, optional ParadeDB pg_search BM25, and optional Apache AGE graph similarity.
Spring Boot auto-configuration wiring FoundgineMcpServer onto foundgine.mcp.path (default /mcp, disabled by default) with origin allowlist validation and Spring Security context bridging.
Exposes Foundgine's six governed MCP tools over HTTP and adapts them into LangChain4j AiServices tool maps with signed fgmcp1 write approvals.
MigrationsCli), and compile-time annotation processor (FoundgineAotProcessor).
Protocol and host adapters wiring GraphQL Java data fetchers, Keycloak OIDC/JWKS token verification, and Temporal workflow orchestration with per-activity warrant re-minting.
CLI tool that diffs a compiled MetadataRegistry against database snapshots to generate deterministic Flyway-compatible SQL migration scripts.
Java javax.annotation.processing.Processor scanning @FoundgineModel and @FoundgineModelEntityMap to generate reflection-free GeneratedFoundgineMetadata at build time.
/mcp) and Temporal workflow routes (/foundgine/workflows).
Zero-dependency Node 20+ / Fetch API client managing MCP sessions, bearer token callbacks, SSE replay, and workflow lifecycle calls.
Python 3.11+ async and sync httpx clients with typed tool wrappers and structured MCP error propagation.
Typed JSON-RPC/HTTP error wrappers, exponential retry/abort signal handlers, and Temporal workflow lifecycle helpers (listProcesses, describe, start, status, decide, cancel) shared identically across TypeScript, Python, and Rust/WASM.
Pure-Rust sans-I/O MCP/workflow protocol state machine compiled to WebAssembly for browsers, Cloudflare Workers, Deno, and Node.
Shared JSON test vectors verifying that C# and Java SemanticQuery builders emit byte-for-byte identical canonical operations.
Regenerates repo-index.json and REPO-MAP.md from repository source files and XML/Javadoc comments.
Foundgine scales incrementally from a single in-process application library with zero external infrastructure up to a horizontally scaled, multi-protocol enterprise execution hub.
Stack: Foundgine.Core + Runtime + EF Core / JPA + PostgreSQL (or SQLite).
FoundgineModel + row-level predicates.Stack: Tier 1 + Hot Chocolate / GraphQL Java + MCP Streamable HTTP + Keycloak + Redis.
/graphql), MCP (/mcp), and MAF / LangChain4j agent loops.AnchoredSecurityWarrantRevocationStore (Redis + PostgreSQL GREATEST epoch) guarantees cluster-wide single-use replay protection and instant revocation.Stack: Tier 2 + PostgresEventStore + PostgresOutbox + Temporal + BufferedDurableAuditLog.
fgmcp1) and AES-256-GCM encrypted gateway envelopes produce immutable audit receipts.| Capability | Foundgine (v3.4.2) | Direct MCP / Tool Wrappers | Semantic Kernel / LangChain | Plain GraphQL + ORM |
|---|---|---|---|---|
| Primary Center of Gravity | Application-owned semantic & execution boundary | Transport protocol for LLM tool calls | LLM prompt/chain orchestration loop | HTTP GraphQL schema & resolver tree |
| Row & Field Security Enforcement | Lowered directly into SQL WHERE / ORM projections via bound ExecutionIR |
Left entirely to custom tool handler code | Left entirely to custom plugin/tool code | Distributed across resolvers/middleware |
| Ambiguous Natural-Language Intent | Fails closed (RequiresClarification) with competing signatures |
Relies on LLM prompt heuristics | Relies on LLM prompt heuristics | Not applicable (strict typed schema) |
| Multi-Step Write Governance | DryRun → SHA-256 PlanFingerprint → signed approval → nonce replay check |
Ad-hoc confirmation flags | Framework-specific human-in-the-loop callbacks | Custom mutation endpoints |
| Dual-Runtime Parity (.NET & Java) | Shared fluent model, AOT generators & JSON conformance vectors | SDK-only protocol parity | Separate architectures (.NET SK vs. Python/Java) | Separate ecosystems (HC vs. GraphQL Java) |
POST /mcp HTTP/1.1
Authorization: Bearer <host-oidc-or-warrant-token>
Content-Type: application/json
Accept: application/json, text/event-stream
{
"jsonrpc": "2.0",
"id": "req-402",
"method": "tools/call",
"params": {
"name": "foundgine_query",
"arguments": {
"expression": "active customers"
}
}
}
{
"jsonrpc": "2.0",
"id": "req-402",
"result": {
"isError": true,
"structuredContent": {
"outcome": "RequiresClarification",
"committed": null,
"reason": "Expression 'active customers' maps to 2 distinct semantic signatures.",
"competingInterpretations": [
{ "signature": "Customer[AccountEnabled == true]", "weight": 90 },
{ "signature": "Customer[Some(orders, PlacedWithinDays <= 90)]", "weight": 85 }
]
}
}
}
{
"receiptId": "rcpt_01JDF8W9K2M4N7P8Q1R3S5T6V7",
"executedAtUtc": "2026-11-26T06:15:00.142Z",
"principal": {
"subject": "user:alice@acme.example",
"tenantId": "tenant-nz-01",
"warrantId": "wrt_9f82c1a4",
"delegationDepth": 1
},
"provenance": {
"contractFingerprint": "sha256:8f4e2b91c0d7...a19c",
"authorizationDecisionFingerprint": "sha256:3c71a904e5b2...77d0",
"planFingerprint": "sha256:6b12f883d9e1...40e8",
"executionIrFingerprint": "sha256:1a94c552f0b8...92f1"
},
"provider": {
"name": "SqlExecutionProvider",
"dialect": "PostgreSQL",
"planCacheHit": true,
"rowsReturned": 24
}
}
dotnet add package Foundgine.Core --version 3.4.2
dotnet add package Foundgine.Runtime --version 3.4.2
dotnet add package Foundgine.Providers --version 3.4.2
dotnet add package Foundgine.Extensions --version 3.4.2
<dependency>
<groupId>io.github.cristianbarragan</groupId>
<artifactId>foundgine-core</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>io.github.cristianbarragan</groupId>
<artifactId>foundgine-runtime</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>io.github.cristianbarragan</groupId>
<artifactId>foundgine-providers</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>io.github.cristianbarragan</groupId>
<artifactId>foundgine-extensions</artifactId>
<version>3.4.2</version>
</dependency>
Beyond synchronous read and mutation execution, Foundgine provides durable event persistence, transactional outbox dispatch, encrypted approval gateways, and native OpenTelemetry instrumentation—all governed by the same frozen semantic contract and host-owned security boundary.
PostgresEventStore)
Appends immutable domain and governance EventEnvelope records into PostgreSQL streams with strict per-stream sequence numbers and optimistic concurrency checks (ExpectedVersion). Supports stream replay, causal correlation IDs (CorrelationId / CausationId), and principal provenance metadata.
PostgresOutbox)
Writes outbound integration messages into the outbox table inside the exact same database transaction as the business entity mutation. Background workers claim batches via FOR UPDATE SKIP LOCKED, enforce idempotency keys, apply exponential retry backoff, and quarantine poison messages to a dead-letter partition.
FoundgineGateway)
Provides a transport-neutral facade for high-assurance workflows where mutation proposals are persisted in PostgresFoundgineGatewayApprovalStore using AES-256-GCM authenticated encryption (key-versioned with AAD bound to tenant and plan fingerprint) until an authorized human or policy engine approves dispatch.
BufferedDurableAuditLog)
Emits distributed traces (ActivitySource("Foundgine") / OpenTelemetry Java SDK) and histograms across every pipeline stage without leaking sensitive row values or raw tokens. BufferedDurableAuditLog batches signed ExecutionReceipt records with bounded backpressure so audit evidence is never silently dropped.
using Foundgine.Providers.Storage.Postgres;
// Register PostgreSQL Event Store, Transactional Outbox & Durable Audit Log
builder.Services.AddFoundginePostgresPersistence(pg =>
{
pg.ConnectionString = configuration.GetConnectionString("FoundgineDb")!;
pg.EnableEventStore = true;
pg.EnableOutbox = true;
pg.OutboxBatchSize = 64;
pg.OutboxMaxAttempts = 8;
pg.EnableDurableAuditLog = true;
pg.AuditFlushInterval = TimeSpan.FromMilliseconds(250);
});
// Outbox rows commit atomically alongside SemanticMutationEngine SQL/EF Core writes,
// then dispatch via FOR UPDATE SKIP LOCKED to Temporal, Kafka, or HTTP webhooks.
using Foundgine.Runtime.Gateway;
using Foundgine.Providers.Storage.Postgres;
// Encrypt stored mutation proposals at rest with key-ring rotation & AAD binding
var keyRing = new AesGcmEnvelopeKeyRing(
activeKeyId: "kek-2026-11",
keys: new Dictionary<string, byte[]>
{
["kek-2026-11"] = Convert.FromBase64String(secretBase64)
});
builder.Services.AddSingleton<IFoundgineGatewayApprovalStore>(sp =>
new PostgresFoundgineGatewayApprovalStore(pgDataSource, keyRing));
| Telemetry Signal | Name / Instrument | Recorded Attributes (PII-Safe) |
|---|---|---|
| Trace Span | foundgine.execute / foundgine.mutation |
foundgine.operation.kind, foundgine.root_entity, foundgine.contract_fp, foundgine.tenant_id |
| Trace Span | foundgine.lexical.ground |
foundgine.grounding.outcome, foundgine.tokens.count, foundgine.paths.explored |
| Trace Span | foundgine.security.authorize |
foundgine.auth.decision, foundgine.warrant.present, foundgine.delegation.depth |
| Histogram | foundgine.execution.duration_ms |
Tags: provider (sql, efcore, jpa), plan_cache_hit, outcome |
| Counter | foundgine.security.denials_total |
Tags: reason (replay, revoked, scope, limit_exceeded, unbound_plan) |
Every Foundgine runtime exposes deterministic configuration switches and typed exception/error categories so host gateways, GraphQL adapters, and MCP clients can distinguish transient infrastructure faults from security rejections or ambiguous user intent.
FoundgineOptions / FoundgineEngineConfig)| Option / Setting | Default | Security & Runtime Behavior |
|---|---|---|
RequireSignedWarrants |
false (direct host code) / true (gateway/MCP) |
When enabled, rejects any SecurityExecutionContext lacking a verified cryptographic warrant from a trusted root issuer. |
MinimumAliasWeight |
75 (range 1..100) |
Minimum lexical evidence score required before SemanticLexicalResolver can commit an alias match without asking for clarification. |
LexicalBudget |
32 tokens · 5,000 paths · 250ms |
Caps search work per grounding call; exceeding any bound aborts with GroundingOutcome.BudgetExceeded. |
EnablePlanCaching |
true |
Caches compiled SQL/ORM shapes keyed by full SemanticPlanAuthorizationBinding fingerprint (never shares plans across differing predicates). |
ResourceLimits |
SecurityResourceLimits.Default |
Enforces structural ceilings on selection depth (32), nodes (256), filter depth (32), page size (1,000), and mutation batch size (128). |
FailClosedOnAuditBackpressure |
true |
Refuses to commit mutations if BufferedDurableAuditLog cannot persist the corresponding signed execution receipt. |
| Error / Outcome Type | HTTP / MCP Status | Trigger Condition | Recommended Caller Action |
|---|---|---|---|
GroundingOutcome.RequiresClarification |
200 (MCP isError: true) |
Free-form query matched ≥2 distinct semantic signatures or fell below MinimumAliasWeight. |
Present CompetingInterpretations to the user or re-submit structured foundgine_query_semantic. |
GroundingOutcome.Unresolved |
400 / 422 |
Unknown entity/field token or unmodeled subjective term (e.g., "big"). |
Inspect Reason for the exact unresolved token and map it to a modeled field or alias. |
SecurityAuthorizationException |
403 Forbidden |
Missing entity/field/hop permission, invalid issuer/audience, or empty authorized projection set. | Do not retry with widened arguments; request an appropriately scoped host token/warrant. |
WarrantReplayDetectedException |
403 Forbidden |
Single-use warrant jti nonce or fgmcp1 approval token was already consumed. |
Re-run dry-run and obtain a fresh single-use approval/warrant from the host authority. |
PlanBindingTamperedException |
403 / 409 Conflict |
MetadataRegistry contract fingerprint or plan digest drifted between planning/dry-run and execution. |
Discard cached plan/approval and re-plan against the current frozen MetadataRegistry. |
ResourceLimitExceededException |
400 / 413 |
Query or mutation exceeded SecurityResourceLimits (depth, node count, page size, cursor length). |
Reduce selection depth, split batch mutations, or paginate with smaller Take/limit. |
In src/csharp/samples/Foundgine.Comparison, both arms run against an identical legacy PostgreSQL schema (tbl_customer, tbl_order.ord_total, tbl_order_line.qty) and identical HS256 JWT tokens:
| Dimension | Foundgine.Shop (Foundgine + Hot Chocolate + EF) | HotChocolate.Shop (Plain Hot Chocolate + EF) |
|---|---|---|
| Where Rules Live | Centralized in ShopModel and ShopAuthorizationPolicy; Hot Chocolate is a thin adapter. |
Inside GraphQL resolvers and EF IQueryable projections. |
| Adding a 2nd Protocol (MCP) | ~15 lines (ShopMcp.cs) exposing /mcp with identical row-level security and zero duplicated rules. |
Requires extracting a separate service/authorization layer or duplicating claim-filtering logic. |
| Sample Code Footprint | 234 non-blank, non-comment C# lines (pays off across multi-surface deployments). | 113 non-blank, non-comment C# lines (more concise when GraphQL is the sole interface). |
Recorded preliminary run (sc-cs-orders-customer, single read query salesOrder(first: 50) with lines and shipments; status: preliminary, not claim-grade) quantifying the per-request semantic planning/warrant boundary cost versus direct Hot Chocolate + EF projection:
| Concurrency | Foundgine RPS | Foundgine p99 | Baseline (HC + EF) RPS | Baseline p99 | Notes |
|---|---|---|---|---|---|
| 1 | 111 rps | 15.8 ms | 254 rps | 8.7 ms | Reflects semantic intent translation, warrant check & plan compilation overhead. |
| 8 | 354 rps | 44.3 ms | 1,086 rps | 16.0 ms | Both cells valid. |
| 16 | 509 rps | 52.9 ms | 1,245 rps | 31.8 ms | Foundgine approaches single-container CPU plateau (~510–522 rps). |
| 32 | 522 rps | 112.5 ms | 369 rps (invalid) | 154.6 ms | Foundgine valid; baseline failed validation gate at c=32. |
Foundgine.RedTeam vs. Foundgine.SupplyChain.Advanced): Across 18 MCP requests (11 semantic API, 7 execution API), both legitimate baselines succeeded (2/2) and 100% of adversarial attempts (15/15 attacks + 1 unauthenticated call)—including cross-tenant probes, identity claim spoofing, scope: * widening, cross-customer order reads, and role escalation—were blocked fail-closed.AgentEndToEnd/Fixtures/SupplyChain.PenTest plus cross-language conformance vectors in src/conformance/.
Foundgine enforces behavioral equivalence between .NET 10 and Java 27 through shared JSON conformance suites under src/conformance/ executed in CI on every commit:
src/conformance/)semantic-query-vectors.json — Verifies identical canonical SemanticOperation ASTs from C# and Java SemanticQuery builders.lexical-grounding-vectors.json — Validates identical Committed, RequiresClarification, Unresolved, and BudgetExceeded decisions under matching budgets.security-limits-vectors.json — Asserts identical rejection thresholds across selection depth, graph nodes, filter depth, and mutation batch bounds.InMemoryExecutionProvider / InMemoryMutationExecutionProvider — Executes full ExecutionIR plans with row-level predicates, joins, tie-breaker sorting, and atomic rollback without external databases.InMemorySecurityWarrantReplayStore & InMemorySecurityWarrantRevocationStore — Deterministic single-use nonce and revocation epoch testing in milliseconds.Foundgine.Core — semantic model, metadata, intent, planning, security contractsFoundgine.Runtime — orchestration, authorization, warrants, control planeFoundgine.Providers — SQL, EF Core, InMemory, Redis, MAF, pgvector, Elasticsearch, MCP, AOT & ORM generatorsFoundgine.Extensions — Hot Chocolate GraphQL, GraphQL HTTP, Keycloak, Temporalio.github.cristianbarragan)foundgine-core — semantic model, metadata, intent, planning, lexical resolverfoundgine-runtime — runtime orchestration, warrant revalidation, governancefoundgine-providers — SQL, InMemory, JPA, MCP, Redis, Spring Boot, LangChain4j, retrievalfoundgine-extensions & foundgine-migrations — GraphQL Java, Keycloak, Temporal, Flyway schema CLI
While Foundgine leaves your domain tables untouched, its optional durability and distributed governance adapters (PostgresEventStore, PostgresOutbox, BufferedDurableAuditLog, PostgresSecurityWarrantRevocationEpochAnchor, and PostgresFoundgineGatewayApprovalStore) use compact, indexed PostgreSQL schemas designed for high-concurrency lock-free claiming and monotonic consistency.
CREATE TABLE IF NOT EXISTS foundgine_outbox (
outbox_id UUID PRIMARY KEY,
idempotency_key TEXT NOT NULL UNIQUE,
topic TEXT NOT NULL,
tenant_id TEXT NOT NULL,
correlation_id TEXT NOT NULL,
payload_json JSONB NOT NULL,
created_at_utc TIMESTAMPTZ NOT NULL DEFAULT NOW(),
available_at_utc TIMESTAMPTZ NOT NULL DEFAULT NOW(),
attempts INT NOT NULL DEFAULT 0,
dispatched_at TIMESTAMPTZ NULL,
dead_lettered_at TIMESTAMPTZ NULL,
last_error TEXT NULL
);
CREATE INDEX IF NOT EXISTS ix_foundgine_outbox_pending
ON foundgine_outbox (available_at_utc, created_at_utc)
WHERE dispatched_at IS NULL AND dead_lettered_at IS NULL;
CREATE TABLE IF NOT EXISTS foundgine_audit_receipts (
receipt_id TEXT PRIMARY KEY,
executed_at_utc TIMESTAMPTZ NOT NULL,
tenant_id TEXT NOT NULL,
subject_id TEXT NOT NULL,
warrant_id TEXT NULL,
contract_fp TEXT NOT NULL,
plan_fp TEXT NOT NULL,
execution_ir_fp TEXT NOT NULL,
operation_kind TEXT NOT NULL,
root_entity TEXT NOT NULL,
rows_affected INT NOT NULL,
receipt_payload JSONB NOT NULL
);
-- Monotonic GREATEST epoch anchor preventing Redis cache lag from resurrecting revoked warrants
CREATE TABLE IF NOT EXISTS foundgine_warrant_revocation_anchor (
issuer_id TEXT PRIMARY KEY,
revocation_epoch BIGINT NOT NULL,
updated_at_utc TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- Atomic upsert advancing epoch monotonically:
-- INSERT INTO foundgine_warrant_revocation_anchor (issuer_id, revocation_epoch)
-- VALUES ($1, $2)
-- ON CONFLICT (issuer_id) DO UPDATE
-- SET revocation_epoch = GREATEST(foundgine_warrant_revocation_anchor.revocation_epoch, EXCLUDED.revocation_epoch),
-- updated_at_utc = NOW();
CREATE TABLE IF NOT EXISTS foundgine_gateway_approvals (
approval_id UUID PRIMARY KEY,
tenant_id TEXT NOT NULL,
plan_fingerprint TEXT NOT NULL,
key_id TEXT NOT NULL,
nonce_iv BYTEA NOT NULL,
ciphertext BYTEA NOT NULL,
auth_tag BYTEA NOT NULL,
expires_at_utc TIMESTAMPTZ NOT NULL,
consumed_at_utc TIMESTAMPTZ NULL
);
CREATE TABLE IF NOT EXISTS foundgine_events (
global_position BIGSERIAL PRIMARY KEY,
stream_id TEXT NOT NULL,
stream_version BIGINT NOT NULL,
event_id UUID NOT NULL UNIQUE,
event_type TEXT NOT NULL,
tenant_id TEXT NOT NULL,
correlation_id TEXT NOT NULL,
causation_id TEXT NULL,
metadata_json JSONB NOT NULL,
payload_json JSONB NOT NULL,
recorded_at_utc TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (stream_id, stream_version)
);
Foundgine's execution boundary is pluggable via a minimal Service Provider Interface (SPI). Custom storage providers (e.g., DuckDB, ClickHouse, Neo4j, or internal gRPC microservices) receive an already-authorized, bound ExecutionIR and must present a valid provider security proof bound to that exact IR fingerprint before returning data.
using Foundgine.Core.Execution;
using Foundgine.Core.Security;
public sealed class CustomAnalyticsExecutionProvider : IExecutionProvider
{
public string ProviderName => "AnalyticsWarehouse";
public async ValueTask<ProviderExecutionResult> ExecuteAsync(
ExecutionIR ir,
ProviderExecutionContext context,
CancellationToken ct)
{
// 1. Refuse execution if plan binding or security proof is absent
ir.EnsureBoundAndVerified(context.SecurityProof);
// 2. Translate ScanNode, PredicateFilterNode (contains mandatory auth predicates),
// ProjectionNode (authorized columns only), and SortNode (includes PK tie-breaker)
var query = TranslateIrToWarehouseQuery(ir);
var rows = await query.RunParameterizedAsync(context.Parameters, ct);
return ProviderExecutionResult.FromRows(rows, planCacheHit: false);
}
}
import com.foundgine.core.execution.*;
import com.foundgine.core.security.*;
public final class CustomWarehouseProvider implements ExecutionProvider {
@Override
public String providerName() {
return "AnalyticsWarehouse";
}
@Override
public ProviderExecutionResult execute(ExecutionIR ir, ProviderExecutionContext context) {
ir.ensureBoundAndVerified(context.securityProof());
var rows = runTranslatedIr(ir, context.parameters());
return ProviderExecutionResult.fromRows(rows, false);
}
}
Select a runtime scenario below to inspect how Foundgine transforms caller input across Stage 2 (Intent), Stage 4 (Operation Graph), Stage 7 (Authorization & Row Predicates), Stage 9 (ExecutionIR), and Stage 12 (Execution Receipt):
// Caller Context (from verified Host JWT / Warrant):
// Subject: "user:alice", TenantId: "nz-auckland-01", Roles: ["sales"]
// Stage 4 OperationGraph Nodes & Edges:
// Root: SalesOrder [Id, OrderNumber, Total]
// └─ Edge (OneToMany via cust_id): OrderLine [Sku, Quantity]
// (Note: UnitCost stripped by policy — requires "finance" role)
// Stage 7 Injected Row-Level Predicate:
// SalesOrder.TenantId == @p_auth_tenant ("nz-auckland-01")
-- Stage 9/10 Lowered PostgreSQL Query (with automatic PK tie-breaker):
SELECT o.ord_id, o.ord_number, o.ord_total
FROM erp.tbl_order o
WHERE o.tenant_id = @p_auth_tenant
AND o.status = @p_filter_0
ORDER BY o.ord_total DESC, o.ord_id ASC
LIMIT @p_take;
-- Stage 12 Receipt:
-- ContractFP: sha256:8f4e...a19c | PlanCacheHit: true | Rows: 18
// Input expression: "show recent high-value orders"
// Token "high-value" has no declared numeric threshold or weighted alias in MetadataRegistry.
// Result: Halts at Stage 6 BEFORE Authorization or SQL Compilation!
{
"outcome": "Unresolved",
"committed": null,
"reason": "Unresolved vocabulary token 'high-value': no declared field, dimension, or weighted alias matches.",
"tokensExplored": 4,
"pathsExplored": 12
}
// Attack: Caller passes filter { "TenantId": "tenant-competitor-99" } in MCP / GraphQL args
// while authenticated JWT carries TenantId = "tenant-acme-01".
//
// 1. Host ISecurityExecutionContextProvider ignores payload tenant claims completely.
// 2. Policy injects mandatory predicate: TenantId == "tenant-acme-01".
// 3. Combined SQL predicate: (TenantId = 'tenant-acme-01') AND (TenantId = 'tenant-competitor-99')
// -> Returns 0 rows deterministically; cross-tenant data is mathematically unreachable.
// 1. Dry-Run computes canonical PlanFingerprint = "sha256:9c41e2...77b4"
// 2. Host signs approval token: "fgmcp1.eyJwbGFuRnAiOiJzaGEyNTY6OWM0MWUyLi4uNzdiNCIsImp0aSI6Im5vbmNlLTg4MSJ9."
// 3. ExecuteApproved verifies:
// [x] RSA-2048+ signature valid
// [x] PlanFingerprint == "sha256:9c41e2...77b4" (zero field/target drift)
// [x] Redis replay store consumes jti "nonce-881" atomically
// [x] PostgreSQL revocation anchor epoch <= warrant rev_seq
// 4. Single BEGIN ... COMMIT inserts PurchaseOrder, PurchaseOrderLine, Outbox row & Audit Receipt.
Foundgine separates cold-path semantic compilation from hot-path parameterized execution so production workloads amortize model validation, graph expansion, and SQL/ORM query generation across thousands of requests per second.
Build MetadataRegistry once at application startup (or via compile-time AOT source generators). Never call new MyModel().Build() per HTTP request—freezing computes the contract SHA-256 fingerprint once and shares immutable lookup tables lock-free across all threads.
SqlExecutionProvider and ORM providers cache compiled query templates under SHA256(ContractFP + PlanBindingFP + Dialect). Subsequent requests with the same structural shape and authorization policy bind new parameter values (@p_auth_tenant, @p_filter_0) directly without re-running SQL compilation.
Configure connection multiplexing (StackExchange.Redis / Lettuce) with sub-second timeouts for warrant replay/revocation checks, and cache Keycloak JWKS signing keys in memory with background refresh so token verification adds <0.1 ms per call.
Using Foundgine.Providers.Aot.Generator (.NET 10) or foundgine-aot-generator (Java 27) eliminates runtime expression reflection and assembly scanning, enabling sub-20 ms container cold starts and minimal RSS memory footprints.
To guarantee identical query semantics across .NET 10, Java 27, PostgreSQL, SQLite, SQL Server, EF Core, and JPA, MetadataRegistry and ExecutionIR normalize all scalar values to a strict canonical type system:
| Canonical IR Type | .NET 10 CLR Type | Java 27 Type | PostgreSQL | SQLite / SQL Server |
|---|---|---|---|---|
SemanticType.String |
string |
java.lang.String |
TEXT / VARCHAR |
TEXT / NVARCHAR |
SemanticType.Int32 / Int64 |
int / long |
Integer / Long |
INT4 / INT8 |
INTEGER / INT / BIGINT |
SemanticType.Decimal |
decimal |
java.math.BigDecimal |
NUMERIC(p,s) |
NUMERIC / DECIMAL(p,s) |
SemanticType.Boolean |
bool |
java.lang.Boolean |
BOOLEAN |
INTEGER (0/1) / BIT |
SemanticType.Uuid |
System.Guid |
java.util.UUID |
UUID |
TEXT / UNIQUEIDENTIFIER |
SemanticType.TimestampUtc |
DateTimeOffset |
java.time.Instant |
TIMESTAMPTZ |
TEXT (ISO-8601) / DATETIMEOFFSET |
Full quantitative data from Foundgine's closed-loop performance harness (benchmarks/) and deterministic adversarial security test suites (Foundgine.RedTeam and AgentEndToEnd/Fixtures/SupplyChain.PenTest).
Measured on the sc-cs-orders-customer workload (salesOrder(first: 50) with nested lines and shipments over PostgreSQL 17, preliminary single-container runs):
| Arm & Concurrency | Throughput (RPS) | p50 Latency | p95 Latency | p99 Latency | p99.9 Latency | Validation Gate |
|---|---|---|---|---|---|---|
| Foundgine (.NET 10) · c=1 | 111 rps | 8.4 ms | 12.9 ms | 15.8 ms | 21.4 ms | PASS (0% err) |
| Baseline (HC + EF) · c=1 | 254 rps | 3.6 ms | 6.4 ms | 8.7 ms | 14.1 ms | PASS (0% err) |
| Foundgine (.NET 10) · c=8 | 354 rps | 21.1 ms | 36.8 ms | 44.3 ms | 58.2 ms | PASS (0% err) |
| Baseline (HC + EF) · c=8 | 1,086 rps | 6.9 ms | 12.4 ms | 16.0 ms | 24.5 ms | PASS (0% err) |
| Foundgine (.NET 10) · c=16 | 509 rps | 29.8 ms | 45.2 ms | 52.9 ms | 71.0 ms | PASS (0% err) |
| Baseline (HC + EF) · c=16 | 1,245 rps | 11.9 ms | 23.7 ms | 31.8 ms | 49.2 ms | PASS (0% err) |
| Foundgine (.NET 10) · c=32 | 522 rps | 58.4 ms | 94.1 ms | 112.5 ms | 146.8 ms | PASS (0% err) |
| Baseline (HC + EF) · c=32 | 369 rps | 82.0 ms | 131.4 ms | 154.6 ms | 218.0 ms | INVALID (gate fail) |
| Pipeline Phase | Typical Warm CPU Time | Amortization Mechanism |
|---|---|---|
| JWT / Warrant Signature & Replay Check | ~0.15 – 0.45 ms | In-memory JWKS / issuer public key cache + pipelined Redis Lua script. |
| OperationGraph Expansion & Policy Auth | ~0.35 – 0.80 ms | Lock-free immutable MetadataRegistry lookups + compiled predicate expressions. |
| Plan Binding & ExecutionIR Lookup | ~0.20 – 0.50 ms | SHA256(ContractFP + PlanBindingFP + Dialect) cache hit skips SQL generation. |
| Receipt Construction & Async Audit Enqueue | ~0.10 – 0.25 ms | Lock-free ring buffer enqueue into BufferedDurableAuditLog. |
Every attack vector below is codified in Foundgine.RedTeam (18 MCP vectors) and SupplyChain.PenTest (14 MCP + GraphQL vectors) and verified to fail closed:
| Attack Category | Adversarial Vector / Payload | Enforcing Boundary Gate | Verified Outcome |
|---|---|---|---|
| Cross-Tenant Read | Filter injects TenantId == "other-tenant" in MCP/GraphQL args |
Host ISecurityExecutionContextProvider + lowered SQL WHERE |
BLOCKED (0 rows) |
| Identity Spoofing | Caller supplies spoofed subject / customer_id in JSON body |
Transport adapters discard payload identity; read verified JWT only | BLOCKED (403) |
| Scope Widening | Delegated child warrant requests scope: "*" or extra entity |
ISecurityWarrantDelegationTrustResolver attenuation check |
BLOCKED (403) |
| Traversal Tunneling | Query traverses Customer.transactions skipping restricted Contract |
SemanticOperationGraph expands all intermediate hops prior to auth |
BLOCKED (403) |
| Column Exfiltration | Selects restricted UnitCost or * wildcard without finance role |
Field projection allowlist & empty-set fail-closed gate | BLOCKED (403) |
| Approval Replay | Re-submits valid fgmcp1 approval token a second time |
Atomic Redis jti single-use nonce consumption |
BLOCKED (Replay) |
| Plan Tampering | Mutates Quantity or target entity after DryRunAsync approval |
SHA-256 PlanFingerprint verification before SQL/ORM dispatch |
BLOCKED (Drift) |
| Ambiguous Injection | Natural-language prompt attempts fuzzy coercion ("active customers") |
SemanticLexicalResolver returns RequiresClarification |
BLOCKED (No Exec) |
| GraphQL Root Bypass | Queries unexposed root field orderLine as customer role |
MapFoundgineGraphQL QueryRootRoles allowlist |
BLOCKED (403) |
| Deep Nesting DoS | Submits 40-level recursive relationship selection or 5,000-node filter | SecurityResourceLimits (max depth 32, max nodes 256) |
BLOCKED (400) |
Foundgine's MCP endpoint (/mcp) implements the MCP 2025-06-18 Streamable HTTP transport with stateful session resumability, origin validation, and cryptographic write approvals.
| HTTP Header / Token Field | Direction | Protocol & Security Semantics |
|---|---|---|
Authorization: Bearer <token> |
Client → Server | Required host OIDC/JWT or cryptographic warrant; mapped into SecurityExecutionContext on every request. |
Mcp-Session-Id |
Server ↔ Client | Cryptographically random session identifier bound to the authenticated principal/tenant; cross-principal session reuse is rejected with 403. |
Last-Event-ID |
Client → Server | Enables deterministic Server-Sent Events (SSE) stream replay after transient network disconnects within the session retention window. |
Origin |
Client → Server | Validated against configured AllowedOrigins allowlist to prevent cross-site browser DNS-rebinding or CSRF attacks against local MCP servers. |
fgmcp1.<payload>.<sig> |
Approval Token | Base64url-encoded JSON payload (planFingerprint, jti, sub, tid, exp) signed with RSA-2048+ PKCS#1 v1.5 SHA-256 by the host governance authority. |
Side-by-side reference of every primary entry point across Foundgine.* (.NET 10) and com.foundgine.* (Java 27):
| Subsystem | .NET 10 (.NET C# 14) | Java 27 |
|---|---|---|
| Model Root | new MyModel().Build() → MetadataRegistry |
new MyModel().build() → MetadataRegistry |
| Fluent Query | SemanticQuery.From(meta, "Entity").Select(...).WhereEq(...).Build() |
SemanticQuery.from(meta, "Entity").select(...).whereEq(...).build() |
| Read Execution | await executor.ExecuteAsync(op, secCtx, ct) |
executor.executeAsync(op, secCtx).join() |
| Lexical Grounding | resolver.Ground(expression, ct) → GroundingDecision |
resolver.ground(expression) → GroundingDecision |
| Mutation Dry-Run | await mutations.DryRunAsync(graph, secCtx, ct) |
mutations.dryRunAsync(graph, secCtx).join() |
| Mutation Execute | await mutations.ExecuteApprovedAsync(approval, secCtx, ct) |
mutations.executeApprovedAsync(approval, secCtx).join() |
| ORM Reader | await efReader.ReadAsync(Entity, q => ..., ct) |
jpaEntities.entity("Entity").read(filters, fields) |
| GraphQL Mount | app.MapFoundgineGraphQL(o => ...) |
FoundgineGraphQlRuntimeWiring.wire(...) |
| Agent Integration | services.AddFoundgineAgentFramework(o => ...) |
FoundgineLangChain4jTools.toolMap(mcpServer) |
Foundgine isolates all cryptographic signing and encryption keys behind pluggable key-provider interfaces so production deployments can back warrant issuance, fgmcp1 approval tokens, and AES-256-GCM gateway envelopes with AWS KMS, Azure Key Vault, Google Cloud KMS, HashiCorp Vault, or PKCS#11 HSMs without exposing raw private key material to application memory.
ISecurityWarrantSigner)RS256 (RSA-2048+ PKCS#1 v1.5 SHA-256), PS256 (RSA-PSS), and ES256 (ECDSA P-256).kid against a multi-key JWKS / trust-root set, allowing new keys to be published before switching the active signing kid.AesGcmEnvelopeKeyRing)tenant_id + plan_fingerprint + approval_id so an encrypted ciphertext row cannot be swapped across tenants or mutation plans in PostgreSQL.using Foundgine.Runtime.Security;
// Configure multiple active/retiring public keys by 'kid' for zero-downtime key rotation
var trustResolver = new StaticWarrantIssuerTrustResolver(options =>
{
options.AddTrustedIssuer("https://auth.acme.example", issuer =>
{
issuer.AddPublicKey("warrant-key-2026-10", retiringRsaPublicKey); // retiring
issuer.AddPublicKey("warrant-key-2026-11", activeRsaPublicKey); // active
issuer.MaxWarrantLifetime = TimeSpan.FromMinutes(5);
});
});
Foundgine.Extensions.GraphQL (Hot Chocolate) and com.foundgine.extensions.graphql (GraphQL Java) project your frozen MetadataRegistry into strongly typed GraphQL query/mutation fields while keeping GraphQL strictly a transport adapter:
QueryRootRoles are exposed at the GraphQL query root; child entities remain navigable strictly through authorized parent relationships.DataFetchingEnvironment / IResolverContext) are translated into SemanticOperation.Selections so only requested, authorized columns are fetched from SQL/EF/JPA—eliminating over-fetching.HasKey) map cleanly to Federation @key reference resolvers, while every subgraph entity fetch still enforces the caller's host-verified SecurityExecutionContext.
Long-running business processes combine PostgresOutbox, Foundgine.Extensions.Temporal / com.foundgine.extensions.temporal, and Foundgine's dry-run/approve/execute mutation lifecycle:
using Temporalio.Activities;
using Foundgine.Extensions.Temporal;
public sealed class FulfillmentActivities(
IFoundgineTemporalAuthorityMinter authorityMinter,
SemanticMutationEngine mutations)
{
[Activity]
public async Task<Guid> ReserveInventoryAsync(ReserveInventoryInput input, CancellationToken ct)
{
// Never serialize warrants in Temporal workflow history; mint a fresh 60s scoped warrant here
SecurityExecutionContext activityContext = await authorityMinter.MintActivityContextAsync(
tenantId: input.TenantId,
subjectId: $"workflow:fulfillment:{input.OrderId}",
allowedEntities: ["InventoryLot", "Shipment"],
ttl: TimeSpan.FromSeconds(60),
ct);
var dryRun = await mutations.DryRunAsync(input.MutationGraph, activityContext, ct);
var approval = await mutations.ApproveAsync(dryRun.PlanFingerprint, activityContext, ct);
var result = await mutations.ExecuteApprovedAsync(approval, activityContext, ct);
return result.PrimaryKey<Guid>("shipment");
}
}
standards/semantic-execution/)
Foundgine's runtime invariants are specified independently of its C# and Java implementations as the normative Semantic Execution Standard (SES) under standards/semantic-execution/. Both Foundgine.* (.NET 10) and com.foundgine.* (Java 27) are validated against these specifications via shared JSON conformance vectors:
| Specification Range | Normative Domain | Core Invariant Enforced |
|---|---|---|
| SES-001 – SES-010 | Semantic Contract, Operation Graph & Monotonic Lifecycle | Frozen MetadataRegistry SHA-256 contract fingerprint; explicit expansion of all multi-hop traversals prior to authorization; strict forward-only pipeline transitions. |
| SES-011 – SES-017 | Bounded Lexical Grounding & Clarification Protocol | Retrieval proposes candidates with evidence scores but never authorizes or guesses; multi-signature ties and sub-threshold weights fail closed with RequiresClarification. |
| SES-018 | Compile-Time AOT Metadata Parity & Zero-Drift | Roslyn source generators and Java annotation processors must emit metadata byte-for-byte semantically identical to fluent runtime builders with zero reflection. |
| SES-019 – SES-024 | Host Security Context, Warrants & Replay Anchors | Transport adapters never manufacture identity; delegated warrants attenuate monotonically; replay nonces and revocation epochs fail closed under cache lag. |
| SES-025 | Provider Fidelity & ExecutionIR Proof Binding | Storage providers execute only bound ExecutionIR artifacts verified by cryptographic security proofs and isolate plan caches by full authorization predicate digest. |
The repository ships paired Starter and Advanced Supply Chain applications in both .NET 10 and Java 27, backed by progressive concept guides (00-Overview-And-Setup.md through 05-Adversarial-Security-Testing.md) and automated test/benchmark runners:
src/csharp/samples/Foundgine.SupplyChain & src/java/samples/foundgine-supply-chain): Minimal realistic boundary exposing fixed tools (get_my_orders, place_order) with single-actor token-to-customer authorization.src/csharp/samples/Foundgine.SupplyChain.Advanced & src/java/samples/foundgine-supply-chain-advanced): Open-intent query and mutation authoring, bounded graph traversal, subtree authorization pruning, BM25/graph candidate retrieval, and adversarial red-team verification.FOUNDGINE_PARADEDB_BM25=1 — Enables ParadeDB pg_search BM25 retrieval integration tests (skips cleanly if extension is absent).FOUNDGINE_POSTGRES_AGE=1 — Enables Apache AGE graph-similarity retrieval tests against PostgreSQL.SUPPLY_CHAIN_CUSTOMERS, SUPPLY_CHAIN_STEPS, SUPPLY_CHAIN_SEED — Controls deterministic stochastic agent workload generation in run-supply-chain.ps1.# Run all .NET 10 concept tests referenced across docs 01–05 (no optional PG extensions required)
cd src/csharp/samples/Foundgine.SupplyChain.Advanced/Semantic
dotnet test Tests/Foundgine.SupplyChain.Advanced.Tests.csproj
# Cross-platform PowerShell (pwsh) end-to-end workload & merged pentest report runners
pwsh ./run-supply-chain.ps1
pwsh ./merge-supply-chain-pentest-report.ps1
| Milestone / Release Line | Key Architectural Capabilities Introduced |
|---|---|
| V2 Baseline | Re-architected around the canonical semantic execution model: frozen semantic contract, SemanticOperationGraph, logical planner, and strict provider boundary. |
| v0.2.x – v0.3.0 | Established initial NuGet release line and added native Model Context Protocol (MCP) provider so agent runtimes consume semantic intents directly. |
| v0.5.x | Introduced the Security Execution Boundary, host-owned SecurityExecutionContext, cryptographic security warrants, and deterministic penetration test suites. |
| v1.0.0 – v2.0.x | Stabilized 1.0 contracts and expanded lexical grounding diagnostics, ambiguity resolution UX, and cross-surface coverage. |
| v3.3.5 – v3.4.2 (Current) | Full dual-runtime parity across .NET 10 and Java 27, SES-018 AOT metadata parity, SES-025 provider execution fidelity, MCP 2025-06-18 Streamable HTTP, and unified Runtime/ControlPlane authority/recovery consolidation. |
Running Foundgine in regulated, high-availability production clusters requires deterministic readiness probes, connection pool budgeting, and ordered shutdown hooks so in-flight mutations and buffered audit receipts drain without data loss:
/health/live): Verifies process responsiveness and frozen MetadataRegistry initialization without touching external dependencies./health/ready): Probes primary database connectivity, Redis warrant replay/revocation store reachability, and PostgreSQL revocation anchor epoch synchronization. Fails closed (503) if Redis lags behind the durable PostgreSQL anchor.SemanticMutationEngine transactions up to ShutdownDrainTimeout.BufferedDurableAuditLog ring buffer to PostgreSQL so every committed receipt is persisted.
Because Foundgine separates semantic identity (MetadataRegistry) from physical storage resolution (IExecutionProvider), a single semantic model can serve three distinct multi-tenant storage isolation patterns without changing application queries or MCP/GraphQL contracts:
| Isolation Model | How Foundgine Enforces Isolation | Best Fit |
|---|---|---|
| Pooled Shared Schema (Row-Level) | ISemanticAuthorizationPolicy injects mandatory resource.TenantId == context.TenantId predicates into ExecutionIR, lowered into parameterized SQL WHERE clauses and optionally paired with PostgreSQL Row-Level Security (RLS). |
High-density SaaS with thousands of tenants sharing a single PostgreSQL cluster. |
| Schema-Per-Tenant | A tenant-aware connection/schema resolver routes ExecutionIR scans onto tenant_<id>.* schemas while keeping plan caches partitioned by tenant schema + plan fingerprint. |
Mid-market enterprise tenants requiring isolated backup/restore boundaries. |
| Database-Per-Tenant | Host DI resolves a tenant-scoped NpgsqlDataSource / DataSource from verified SecurityExecutionContext.TenantId before provider dispatch. |
Strict data-residency or sovereign-cloud tenants (e.g., AU/NZ vs. EU regions). |
In addition to human-readable HTML documentation, the Foundgine repository publishes four synchronized machine-readable discovery artifacts so IDE agents, autonomous coding tools, and MCP clients can inspect capabilities without scraping HTML:
| Artifact Path | Format | Purpose & Automated Maintenance |
|---|---|---|
docs-site/llms.txt |
text/plain |
Concise structured index of Foundgine's architecture, core packages, invariants, and canonical links following the llms.txt convention. |
docs-site/llms-full.md |
text/markdown |
Complete, single-file technical reference containing full code examples, configuration tables, and security rules for large-context LLM ingestion. |
.well-known/mcp.json |
application/json |
Standard MCP server discovery manifest advertising transport capabilities (2025-06-18), endpoint paths (/mcp), and the six governed tool schemas. |
repo-index.json & REPO-MAP.md |
JSON & Markdown |
Complete file, namespace, and symbol inventory generated automatically by python tools/generate-repo-index.py. |
Foundgine's deterministic execution boundary, row-level predicate lowering, and tamper-evident audit receipts map directly onto enterprise security and privacy controls:
| Control Framework | Requirement / Risk | Foundgine Architectural Control |
|---|---|---|
| OWASP LLM01 / LLM06 (Prompt Injection & Excessive Agency) |
Untrusted user prompts attempt to invoke unauthorized tools, exfiltrate cross-tenant records, or trigger unapproved state mutations. | Untrusted input is isolated to intent/lexical parsing; ambiguous queries fail closed (RequiresClarification); reads enforce SQL-lowered row/column policies; writes require dry-run PlanFingerprint + host-signed fgmcp1 approval. |
| OWASP API1 / API3 (BOLA / BOPLA) |
Broken Object-Level or Property-Level Authorization across GraphQL or REST/MCP endpoints. | SemanticOperationGraph expands all intermediate traversal hops before authorization; policies return explicit column allowlists and mandatory object-level predicates lowered into SQL WHERE. |
| SOC 2 Type II / ISO 27001 (Access Control & Auditability) |
Demonstrable least-privilege enforcement, revocation timeliness, and immutable audit trails of data access and mutations. | Short-lived cryptographic warrants with delegation attenuation, Redis + PostgreSQL GREATEST monotonic revocation epochs, and lossless BufferedDurableAuditLog receipts recording contract, plan, and IR SHA-256 digests. |
| GDPR / NZ Privacy Act 2020 (Data Minimization & Residency) |
Preventing over-fetching of PII fields and enforcing regional tenant data boundaries. | Field projection pruning ensures unauthorized or unrequested PII columns are never selected from storage; database-per-tenant routing isolates regional storage backends by verified TenantId. |
Reproducible build and verification commands across all five language ecosystems in the Foundgine monorepo (v3.4.2):
# .NET 10 Release Build & Conformance / Security Suites
dotnet test src/csharp/Foundgine.sln -c Release
# Native AOT Publish Verification (Zero-Reflection Source Generator)
dotnet publish src/csharp/samples/Foundgine.SupplyChain -c Release -p:PublishAot=true
# Java 27 Maven Verify (Core, Runtime, Providers, Extensions, AOT & Conformance)
mvn -f src/java/pom.xml -B verify
# TypeScript (@foundgine/typescript)
npm --prefix src/typescript ci && npm --prefix src/typescript test
# Python (foundgine)
pytest src/python/tests
# Rust + WebAssembly (@foundgine/wasm)
cargo test --manifest-path src/wasm/Cargo.toml
mcr.microsoft.com/dotnet/aspnet:10.0-noble-chiseled or eclipse-temurin:27-jre-alpine), mount TLS/JWKS trust bundles read-only, inject KMS/AES-GCM key material via secret managers rather than environment variables, and bind /mcp strictly behind authenticated reverse proxies with explicit AllowedOrigins.
Complete .NET 10 Program.cs composition uniting PostgreSQL, EF Core, Keycloak OIDC, Redis + PostgreSQL Warrant Revocation, Hot Chocolate GraphQL, MCP Streamable HTTP, and Microsoft Agent Framework (MAF) over a single frozen MetadataRegistry:
var builder = WebApplication.CreateBuilder(args);
// 1. Freeze Semantic Model once at startup (or use compile-time AOT GeneratedFoundgineMetadata.Create())
MetadataRegistry metadata = new SupplyChainModel().Build();
builder.Services.AddSingleton(metadata);
// 2. Host-owned Security Context (Keycloak OIDC claims) & Row/Column Authorization Policy
builder.Services.AddFoundgineKeycloakContext(builder.Configuration.GetSection("Keycloak"));
builder.Services.AddSingleton<ISemanticAuthorizationPolicy, SupplyChainAuthorizationPolicy>();
// 3. Persistence (PostgreSQL + EF Core + Outbox + Lossless Audit Log) & Redis-Anchored Revocation
builder.Services.AddFoundginePostgresPersistence(pg =>
{
pg.ConnectionString = builder.Configuration.GetConnectionString("Default")!;
pg.EnableOutbox = true;
pg.EnableDurableAuditLog = true;
});
builder.Services.AddFoundgineAnchoredRevocation(
redisConnection: builder.Configuration.GetConnectionString("Redis")!,
postgresConnection: builder.Configuration.GetConnectionString("Default")!);
// 4. Register Core Runtime, GraphQL Adapter, MCP Server & Microsoft Agent Framework Tools
builder.Services.AddFoundgineRuntime();
builder.Services.AddFoundgineGraphQL(gql => gql.QueryRootRoles.Add("SalesOrder", ["sales", "finance"]));
builder.Services.AddFoundgineMcpServer(mcp => mcp.AllowedOrigins = ["https://app.acme.example"]);
builder.Services.AddFoundgineAgentFramework();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
// 5. Expose identical governed domain capabilities across GraphQL and MCP
app.MapFoundgineGraphQL("/graphql");
app.MapFoundgineMcp("/mcp");
app.Run();
Copy-pasteable, production-ready recipes covering Java 27 + Spring Boot + JPA + MCP, TypeScript / Python / Rust-WASM client SDKs, custom BM25/pgvector candidate retrieval sources, and deterministic security unit tests:
package com.acme.supplychain.config;
import com.foundgine.core.metadata.MetadataRegistry;
import com.foundgine.runtime.FoundgineEngine;
import com.foundgine.providers.jpa.JpaOrmProvider;
import com.foundgine.providers.mcp.FoundgineMcpServer;
import com.foundgine.providers.langchain4j.FoundgineLangChain4jTools;
import com.foundgine.extensions.keycloak.KeycloakContextProvider;
import jakarta.persistence.EntityManagerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FoundgineConfiguration {
@Bean
public MetadataRegistry metadataRegistry() {
// Freeze semantic contract once at startup (or use compile-time GeneratedFoundgineMetadata.build())
return new SupplyChainModel().build();
}
@Bean
public FoundgineEngine foundgineEngine(
MetadataRegistry registry,
EntityManagerFactory emf,
ErpAuthorizationPolicy authPolicy) {
var jpaProvider = new JpaOrmProvider(emf, registry);
return FoundgineEngine.builder(registry)
.authorizationPolicy(authPolicy)
.executionProvider(jpaProvider)
.mutationProvider(jpaProvider)
.build();
}
@Bean
public FoundgineMcpServer foundgineMcpServer(
FoundgineEngine engine,
KeycloakContextProvider keycloakContextProvider) {
return FoundgineMcpServer.builder(engine)
.securityContextProvider(keycloakContextProvider)
.allowedOrigins(java.util.List.of("https://portal.acme.example"))
.build();
}
@Bean
public java.util.Map<String, dev.langchain4j.agent.tool.ToolSpecification> agentTools(
FoundgineMcpServer mcpServer) {
return FoundgineLangChain4jTools.toolMap(mcpServer);
}
}
import { FoundgineMcpClient } from "@foundgine/typescript";
const client = new FoundgineMcpClient({
endpoint: "https://api.acme.example/mcp",
bearerToken: async () => await auth.getAccessToken(),
});
// 1. Discover frozen capabilities & query with row-level policy enforcement
const orders = await client.querySemantic({
entity: "PurchaseOrder",
select: ["Id", "OrderNumber", "Status", "Total"],
where: [{ field: "Status", op: "Eq", value: "OVERDUE" }],
take: 25,
});
// 2. Two-phase mutation: Dry-Run -> Host Approval Token -> Commit
const preview = await client.mutateDryRun({
entity: "PurchaseOrder",
action: "Update",
key: orders.rows[0].Id,
values: { Status: "ESCALATED" },
});
const approvalToken = await hostGovernance.requestApproval(preview.planFingerprint);
const receipt = await client.mutateExecute({ approvalToken });
# Python (foundgine) — Async MCP & Temporal Workflow Client
from foundgine import AsyncFoundgineClient
async with AsyncFoundgineClient("https://api.acme.example/mcp", token=jwt) as fg:
res = await fg.query("active customers")
if res.outcome == "RequiresClarification":
for opt in res.competing_interpretations:
print(opt.signature, opt.weight)
# Rust + WebAssembly (@foundgine/wasm)
# let client = FoundgineClient::new("https://api.acme.example/mcp", jwt)?;
# let rows = client.query_semantic(spec_json).await?;
using Foundgine.Core.Grounding;
using Npgsql;
// Retrieval proposes weighted lexical candidates only — NEVER bypasses SemanticLexicalResolver or Policy!
public sealed class PostgresFuzzyCandidateSource(NpgsqlDataSource dataSource) : ISemanticLexicalCandidateSource
{
public async ValueTask<IReadOnlyList<LexicalCandidate>> FindCandidatesAsync(
LexicalCandidateRequest request,
CancellationToken ct)
{
await using var conn = await dataSource.OpenConnectionAsync(ct);
await using var cmd = new NpgsqlCommand("""
SELECT canonical_entity, canonical_field, alias_term,
ROUND(similarity(alias_term, @q) * 100)::int AS score
FROM semantic_vocabulary_index
WHERE similarity(alias_term, @q) >= 0.35
ORDER BY score DESC
LIMIT @limit
""", conn);
cmd.Parameters.AddWithValue("q", request.NormalizedToken);
cmd.Parameters.AddWithValue("limit", request.MaxCandidates);
var results = new List<LexicalCandidate>();
await using var reader = await cmd.ExecuteReaderAsync(ct);
while (await reader.ReadAsync(ct))
{
results.Add(new LexicalCandidate(
Entity: reader.GetString(0),
Field: reader.IsDBNull(1) ? null : reader.GetString(1),
MatchedTerm: reader.GetString(2),
EvidenceWeight: reader.GetInt32(3)));
}
return results;
}
}
using Foundgine.Core.Query;
using Foundgine.Core.Security;
using Foundgine.Runtime.Execution;
using Xunit;
public sealed class TenantIsolationPenTest
{
[Fact]
public async Task CrossTenantFilterInjection_CannotBypassHostSecurityContext()
{
var metadata = new SupplyChainModel().Build();
var executor = TestHarness.CreateInMemoryExecutor(metadata, new SupplyChainAuthorizationPolicy());
// Host verifies caller belongs strictly to 'tenant-alpha'
var hostContext = new SecurityExecutionContext(
SubjectId: "user:alice",
TenantId: "tenant-alpha",
Roles: ["sales"],
IsAuthenticated: true);
// Attacker injects explicit filter targeting 'tenant-bravo'
var maliciousQuery = SemanticQuery.From(metadata, "SalesOrder")
.Select("Id", "OrderNumber", "Total")
.WhereEq("TenantId", "tenant-bravo")
.Build();
var result = await executor.ExecuteAsync(maliciousQuery, hostContext, CancellationToken.None);
// Lowered predicate becomes: (TenantId == 'tenant-alpha') AND (TenantId == 'tenant-bravo') -> 0 rows
Assert.Empty(result.Rows);
}
}
Before ExecutionIRCompiler lowers a SemanticPlan into physical SQL or ORM expression trees, SemanticPlanner executes a deterministic sequence of invariant-preserving rewrite passes. Every rewrite pass must preserve the exact SemanticPlanAuthorizationBinding fingerprint and never widen field projections or drop row-level predicates:
| Optimizer Pass | Transformation Performed | Safety Invariant |
|---|---|---|
| 1. Projection Pruning | Removes unreferenced columns from intermediate join nodes while retaining foreign-key join columns and the root primary key. | Never adds columns outside AuthorizationDecision.AllowedFields. |
| 2. Predicate Pushdown | Pushes user filters and policy-injected row-level predicates (TenantId, ownership predicates) as close to base ScanNode leaves as relational semantics allow. |
Never reorders across outer-join null-producing boundaries in a way that alters row visibility. |
| 3. Redundant Join Elimination | Collapses duplicate relationship traversals referencing the same parent/child edge within a single query graph into one JoinNode. |
Preserves cardinalities (OneToOne, ManyToOne, OneToMany) and child row predicates. |
| 4. Deterministic Tie-Breaker Injection | Appends the entity primary key (ASC) to SortNode whenever user sort keys are non-unique or omitted. |
Guarantees stable keyset cursor pagination across concurrent inserts/updates. |
| 5. Cardinality & Depth Guard | Verifies total expanded join fan-out, selection depth (≤32), and node count (≤256) against SecurityResourceLimits. |
Halts with ResourceLimitExceededException before hitting the database. |
Foundgine.Extensions.Keycloak (.NET 10) and com.foundgine.extensions.keycloak (Java 27) bridge verified OIDC access tokens into immutable SecurityExecutionContext records while rejecting unsigned, expired, or wrong-audience tokens at the boundary:
iss) against a strict allowlist of trusted Keycloak realms, caching each realm's JWKS keys independently.act (actor) claim chain is recorded in SecurityExecutionContext.DelegationChain for monotonic attenuation checks.| Variable / Setting | Default | Purpose |
|---|---|---|
ASPNETCORE_URLS / SERVER_PORT |
http://localhost:8080 |
Host HTTP listener exposing /graphql, /mcp, and /health/*. |
FOUNDGINE_MCP_PATH |
/mcp (disabled by default in Spring Boot) |
Streamable HTTP endpoint path for MCP JSON-RPC 2.0 & SSE sessions. |
FOUNDGINE_PARADEDB_BM25 |
0 (unset) |
Enables ParadeDB pg_search BM25 approximate candidate retrieval tests. |
FOUNDGINE_POSTGRES_AGE |
0 (unset) |
Enables Apache AGE openCypher graph similarity retrieval tests. |
OTEL_EXPORTER_OTLP_ENDPOINT |
Unset | Exports ActivitySource("Foundgine") traces and security denial metrics via OTLP. |
Beneath the four top-level NuGet and Maven distribution packages, Foundgine decomposes responsibilities into tightly scoped internal modules so core contracts remain dependency-free while storage, ORM, AOT, GraphQL, MCP, and control-plane modules stay cleanly isolated:
| Architectural Layer | .NET 10 Module / Assembly | Java 27 Maven Module (io.github.cristianbarragan) |
Responsibility |
|---|---|---|---|
| Core Abstractions & Metadata | Core.Abstractions, Core.Semantic.Metadata |
foundgine-core (.abstractions, .metadata) |
Stable identifiers, contract fingerprints, fluent model builder, and frozen MetadataRegistry. |
| Semantic Meaning & Planning | Core.Semantic, Core.Semantic.Planning, Core.Serialization |
foundgine-core (.semantic, .planning, .serialization) |
Intent normalization, lexical grounding, operation graph expansion, logical planning, and JSON intent adapters. |
| Execution IR & Boundary | Core.Execution |
foundgine-core (.execution) |
ExecutionIR algebraic nodes, provider security proof gates, results, and signed ExecutionReceipt evidence. |
| Runtime & Control Plane | Foundgine, Foundgine.Runtime, Runtime.ControlPlane |
foundgine-runtime (.controlplane) |
Application orchestration, authorization enforcement, dry-run/approve/execute mutations, warrant verification, and recovery/authority control-plane state. |
| SQL, InMemory & ORM Providers | Providers.Storage.Sql, Providers.Storage.InMemory, Providers.Orm, Providers.EntityFrameworkCore |
foundgine-providers (storage/sql, storage/inmemory, storage/orm, storage/orm/jpa) |
Parameterized SQL/PostgreSQL lowering, deterministic in-memory execution, and EF Core / JPA ORM adapters. |
| Compile-Time AOT & Generators | Providers.Aot, Providers.Aot.Generator |
foundgine-aot-generator |
Zero-reflection C# Roslyn source generator and Java annotation processor emitting SES-018 compliant metadata builders. |
| MCP, AI Models & GraphQL | Providers.Tools.MCP, Providers.Models, Extensions.GraphQL.HotChocolate* |
foundgine-providers (mcp, langchain4j), foundgine-extensions (graphql, keycloak, temporal) |
MCP 2025-06-18 server/tools, Microsoft.Extensions.AI / MAF / LangChain4j adapters, and Hot Chocolate / GraphQL Java execution boundaries. |
Complete Maven pom.xml and docker-compose.yml setup from src/java/samples/foundgine-supply-chain-advanced/ showing how to wire foundgine-core, foundgine-runtime, and compile-time foundgine-aot-generator annotation processing against PostgreSQL:
<dependencies>
<dependency>
<groupId>io.github.cristianbarragan</groupId>
<artifactId>foundgine-core</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>io.github.cristianbarragan</groupId>
<artifactId>foundgine-runtime</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>io.github.cristianbarragan</groupId>
<artifactId>foundgine-aot-generator</artifactId>
<version>3.4.2</version>
</path>
</annotationProcessorPaths>
<compilerArgs>
<arg>-Afoundgine.generated.package=com.foundgine.samples.supplychain.advanced.generated</arg>
</compilerArgs>
</configuration>
</plugin>
</plugins>
</build>
services:
postgres:
image: postgres:16
environment:
POSTGRES_DB: foundgine_supply_chain
POSTGRES_USER: foundgine
POSTGRES_PASSWORD: foundgine
ports:
- "4429:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U foundgine -d foundgine_supply_chain"]
interval: 2s
timeout: 3s
retries: 20
# Start database and verify health before running E2E / PenTest suites:
# docker compose up -d postgres
Foundgine enforces strict separation of concerns across seven normative concepts so retrieval, model output, and transport framing can never be conflated with domain authority:
| Term | Normative Definition & Boundary Rule |
|---|---|
| Intent | What the caller requests (SemanticOperation / SemanticMutationIntent), expressed independently of physical SQL tables, ORM entities, or transport wire formats. |
| Retrieval | Approximate candidate discovery plus evidence scores (e.g., BM25, pg_trgm, pgvector, or Apache AGE). Retrieval only ever proposes candidates—it never decides meaning or grants authorization. |
| Resolution (Grounding) | Evaluates lexical candidates against the frozen MetadataRegistry and relationship graph; commits only when a single canonical semantic signature clears threshold, otherwise fails closed with RequiresClarification. |
| Authorization | Evaluates host-verified SecurityExecutionContext, cryptographic warrants, and domain policies to determine permitted entities, fields, traversal hops, and mandatory row-level predicates. |
| Plan | Provider-independent logical execution plan (SemanticPlan) cryptographically bound via SemanticPlanAuthorizationBinding to the contract and authorization decision digests. |
| ExecutionIR | Controlled algebraic intermediate representation at the storage provider boundary; providers translate bound ExecutionIR mechanically without re-interpreting caller authority. |
| Evidence | Structured audit record (ExecutionReceipt / ExecutionEvidence) capturing what was resolved, authorized, and executed—recorded for compliance without granting downstream authority. |
docs/APPLICATION-CATEGORIES.md)
Foundgine centralizes semantic meaning, relationship traversal, and row-level authorization without making any single transport or database the center of your architecture. Use this matrix from docs/WHY-FOUNDGINE.md and docs/APPLICATION-CATEGORIES.md to evaluate architectural fit:
| Application Category | Architectural Problem Solved | Recommended Foundgine Footprint |
|---|---|---|
| Multi-Surface Domain Backends (REST + GraphQL + Internal Services) |
Eliminates duplicated entity definitions, relationship traversal rules, filter validation, and authorization checks across separate transport layers. | Foundgine.Core + Foundgine.Runtime + EF Core / JPA + GraphQL adapter. |
| AI-Enabled & MCP-Exposed Applications | Lets AI agents express open intent while ensuring retrieval never grants authority and ambiguous phrasing fails closed (RequiresClarification). |
Full boundary + Providers.Tools.MCP (/mcp) + host-minted warrants + fgmcp1 write approvals. |
| Regulated Multi-Tenant SaaS | Guarantees tenant isolation and property-level redaction by lowering host-verified predicates directly into SQL WHERE and recording immutable receipts. |
ISemanticAuthorizationPolicy + SQL/EF/JPA providers + BufferedDurableAuditLog. |
| Legacy Database Modernization | Exposes clean domain entities and weighted aliases over legacy table/column schemas without rewriting existing databases or ORMs. | Fluent FoundgineModel physical table/column mappings + compile-time AOT generators. |
| Simple Single-Endpoint CRUD / Public Read | Minimal domain rules, single consumer surface, and no row/column security boundaries. | Not required—plain ASP.NET Core / Spring Web + ORM is simpler and sufficient. |
Both runtimes include an optional ControlPlane module outside the core synchronous query execution path, intentionally scoped to distinct operational responsibilities in each ecosystem:
Foundgine.Runtime.ControlPlaneOptional cluster recovery and high-availability coordination module remaining strictly outside the core semantic authorization path:
com.foundgine.runtime.controlplaneOptional governance and key-lifecycle module tailored for JVM enterprise hosts:
FoundgineGraphQLQueryExecutor & MutationExecutor)
GraphQL adapters never trust GraphQL query text, operation names, variables, or field arguments as sources of identity or tenant authority. Every GraphQL operation routes through dedicated boundary executors requiring a host-supplied ISecurityExecutionContextProvider:
using Foundgine.Extensions.GraphQL;
using Foundgine.Core.Security;
// GraphQL variables & arguments are parsed strictly as untrusted intent/filter values.
// Identity, TenantId, and Roles are resolved exclusively by host ISecurityExecutionContextProvider.
public sealed class OrderGraphQlEndpoint(
FoundgineGraphQLQueryExecutor queryExecutor,
FoundgineGraphQLMutationExecutor mutationExecutor,
ISecurityExecutionContextProvider hostSecurityProvider)
{
public async ValueTask<GraphQlExecutionResponse> ExecuteQueryAsync(
GraphQlExecutionRequest request,
CancellationToken ct)
{
SecurityExecutionContext trustedContext =
await hostSecurityProvider.GetCurrentContextAsync(ct);
// Enforces QueryRootRoles, SecurityResourceLimits, OperationGraph traversal auth,
// and SQL-lowered row/column predicates identically to MCP and C# callers.
return await queryExecutor.ExecuteAsync(request, trustedContext, ct);
}
}
Beyond flat single-table reads, SemanticQuery and ExecutionIRCompiler support multi-hop relationship traversals, relational quantifiers (Some, Every, None), and bounded scalar aggregations—all subject to per-hop authorization and row-level predicate injection:
// Find customers with at least one overdue order over $1,000 AND no open compliance holds.
// SemanticOperationGraph expands Customer -> SalesOrder and Customer -> ComplianceHold
// so both target entities and intermediate FK edges are authorized before SQL lowering.
var query = SemanticQuery.From(metadata, "Customer")
.Select("Id", "Name", "AccountTier")
.WhereRelatedSome("orders", order =>
order.WhereEq("Status", "OVERDUE")
.WhereGt("Total", 1000m))
.WhereRelatedNone("complianceHolds", hold =>
hold.WhereEq("Resolved", false))
.OrderByAsc("Name")
.Take(50)
.Build();
SELECT c.cust_id, c.cust_name, c.account_tier
FROM erp.tbl_customer c
WHERE c.tenant_id = @p_auth_tenant
AND EXISTS (
SELECT 1 FROM erp.tbl_order o
WHERE o.cust_id = c.cust_id
AND o.tenant_id = @p_auth_tenant
AND o.ord_status = @p_0
AND o.ord_total > @p_1
)
AND NOT EXISTS (
SELECT 1 FROM erp.tbl_compliance_hold h
WHERE h.cust_id = c.cust_id
AND h.tenant_id = @p_auth_tenant
AND h.is_resolved = @p_2
)
ORDER BY c.cust_name ASC, c.cust_id ASC
LIMIT @p_take;
Foundgine.Core.Serialization (.NET 10) and com.foundgine.core.serialization (Java 27) define a deterministic, schema-validated JSON wire representation for SemanticOperation and SemanticMutationIntent. Both runtimes produce identical canonical JSON bytes and SHA-256 digests for equivalent queries:
{
"schemaVersion": "3.4",
"kind": "Query",
"rootEntity": "SalesOrder",
"selections": ["Id", "OrderNumber", "Status", "Total"],
"filter": {
"op": "And",
"clauses": [
{ "field": "Status", "op": "In", "values": ["PENDING", "APPROVED"] },
{ "field": "Total", "op": "Between", "min": 100.00, "max": 25000.00 }
]
},
"includes": [
{
"relationship": "lines",
"selections": ["Sku", "Quantity"],
"take": 20
}
],
"orderBy": [
{ "field": "Total", "direction": "Desc" }
],
"take": 50
}
Foundgine's security posture covers both runtime execution invariants and software supply-chain integrity (SECURITY.md):
SECURITY.md)Foundgine.RedTeam and src/conformance/.Foundgine.Core and foundgine-core maintain minimal external dependencies to minimize transitive CVE exposure.dero), Maven Central artifacts (io.github.cristianbarragan), npm packages (@foundgine/*), and PyPI releases (foundgine) are built from tagged releases in CI with reproducible SourceLink / GPG signatures.
Complex business mutations rarely touch a single row. SemanticMutationGraph models multi-entity writes as a directed acyclic graph (DAG) of dependent operations—such as inserting a parent PurchaseOrder, capturing its generated primary key, inserting child PurchaseOrderLine rows, updating inventory reservations, and appending a transactional outbox event inside one atomic database transaction:
UUID / BIGINT) from parent mutation nodes into child foreign-key slots without exposing intermediate SQL to the caller.ISemanticAuthorizationPolicy, with row-level predicates injected into UPDATE/DELETE WHERE clauses.using Foundgine.Core.Mutations;
using Foundgine.Runtime.Mutations;
// Build a two-step transactional mutation graph: PurchaseOrder + PurchaseOrderLine
var orderId = Guid.NewGuid();
var mutationGraph = SemanticMutationGraphBuilder.Create(metadata)
.Insert("PurchaseOrder", nodeKey: "order", values: new Dictionary<string, object?>
{
["Id"] = orderId,
["CustomerId"] = customerId,
["Status"] = "SUBMITTED",
["Total"] = 2450.00m
})
.Insert("PurchaseOrderLine", nodeKey: "line1", values: new Dictionary<string, object?>
{
["Id"] = Guid.NewGuid(),
["PurchaseOrderId"] = orderId,
["Sku"] = "SKU-9001",
["Quantity"] = 5,
["UnitPrice"] = 490.00m
})
.Build();
// 1. Dry-Run authorizes every node/field & computes deterministic SHA-256 PlanFingerprint
MutationDryRunResult preview = await mutations.DryRunAsync(mutationGraph, hostContext, ct);
// 2. Host governance signs fgmcp1 approval token bound to preview.PlanFingerprint
SignedMutationApproval approval = await hostApprover.SignApprovalAsync(preview, hostContext, ct);
// 3. Atomic commit executes both inserts + outbox + durable audit receipt in one DB transaction
MutationExecutionResult committed = await mutations.ExecuteApprovedAsync(approval, hostContext, ct);
In horizontally scaled clusters, single-use warrant replay defense and instant revocation require atomic check-and-set semantics across all replicas without split-brain race conditions. AnchoredSecurityWarrantRevocationStore pairs an atomic Redis Lua evaluation script with PostgreSQL's durable GREATEST epoch anchor:
-- KEYS[1] = "fg:warrant:jti:<jti>" (single-use replay key)
-- KEYS[2] = "fg:warrant:revoked:<warrantId>" (explicit warrant revocation key)
-- KEYS[3] = "fg:issuer:epoch:<issuerId>" (cached monotonic revocation epoch)
-- ARGV[1] = ttl_seconds, ARGV[2] = token_rev_seq, ARGV[3] = pg_anchor_epoch
if redis.call("EXISTS", KEYS[2]) == 1 then
return {0, "WARRANT_REVOKED"}
end
local cached_epoch = tonumber(redis.call("GET", KEYS[3]) or "0")
local effective_epoch = math.max(cached_epoch, tonumber(ARGV[3]))
if tonumber(ARGV[2]) < effective_epoch then
return {0, "EPOCH_SUPERSEDED"}
end
if redis.call("SET", KEYS[1], "1", "NX", "EX", tonumber(ARGV[1])) == false then
return {0, "REPLAY_DETECTED"}
end
return {1, "OK"}
Direct traceability matrix mapping each core Foundgine security and execution invariant to its normative specification, `.NET 10` assembly, `Java 27` package, and automated verification suite:
| Invariant | SES Spec | .NET 10 Location | Java 27 Location | Verification Suite |
|---|---|---|---|---|
| Frozen Contract Fingerprint | SES-001..004 | Core.Semantic.Metadata |
com.foundgine.core.metadata |
src/conformance/ + AOT parity tests |
| Fail-Closed Ambiguity Gate | SES-011..017 | Core.Semantic.Grounding |
com.foundgine.core.grounding |
lexical-grounding-vectors.json |
| Compile-Time AOT Parity | SES-018 | Providers.Aot.Generator |
foundgine-aot-generator |
SupplyChain.Advanced AOT parity tests |
| Host Context & Warrant Chain | SES-019..024 | Runtime.Security |
com.foundgine.runtime.security |
Foundgine.RedTeam + SupplyChain.PenTest |
| Bound ExecutionIR & Plan Cache | SES-025 | Core.Execution + Storage.Sql |
com.foundgine.core.execution |
ExecutionIR proof & cache isolation tests |
Foundgine supports hybrid lexical, full-text, BM25, dense vector, and graph-neighborhood retrieval while strictly enforcing the invariant that retrieval never decides meaning or grants authority. All candidate sources implement ISemanticLexicalCandidateSource or IApproximateCandidateSource and feed normalized evidence scores into SemanticLexicalResolver:
| Candidate Source Adapter | Storage / Engine | Scoring Mechanism | Boundary Guardrail |
|---|---|---|---|
| In-Memory Exact & Weighted Alias Index | MetadataRegistry (lock-free) |
Declared entity/field names + explicit WithAlias(..., weight) weights (1..100). |
Zero external I/O; deterministic sub-millisecond baseline. |
| PostgreSQL Trigram & FTS | pg_trgm + tsvector |
Trigram similarity & ts_rank_cd normalized onto 0..100 scale. |
Capped by RetrievalTimeout = 2s; unknown tokens still fail closed. |
| ParadeDB BM25 Search | pg_search (FOUNDGINE_PARADEDB_BM25=1) |
BM25 lexical relevance scoring over domain catalog terms and descriptions. | Scores serve strictly as candidate proposals; multi-signature ties trigger RequiresClarification. |
PostgreSQL Dense Vector (pgvector) |
pgvector HNSW / IVFFlat |
Cosine similarity against pre-embedded schema/alias descriptions. | Vector similarity alone cannot override minimumAliasWeight or bypass row predicates. |
| Apache AGE Graph Similarity | age openCypher (FOUNDGINE_POSTGRES_AGE=1) |
Structural neighborhood proximity across domain entity graphs. | Every traversed edge must still exist in frozen MetadataRegistry and pass policy authorization. |
Every committed read and mutation emits an immutable ExecutionReceipt / ExecutionEvidence record binding the frozen contract fingerprint, authorization decision digest, logical plan digest, and lowered ExecutionIR digest. Compliance auditors and automated verification jobs can validate historical receipts against the active MetadataRegistry and policy engine:
using Foundgine.Runtime.Audit;
// Verify that a persisted ExecutionReceipt matches the expected frozen contract fingerprint
// and carries non-empty cryptographic provenance hashes across all four pipeline boundaries.
public static bool VerifyReceiptIntegrity(
ExecutionReceipt receipt,
MetadataRegistry expectedRegistry)
{
if (!string.Equals(receipt.ContractFingerprint, expectedRegistry.ContractFingerprint, StringComparison.Ordinal))
return false;
return !string.IsNullOrWhiteSpace(receipt.AuthorizationDecisionFingerprint)
&& !string.IsNullOrWhiteSpace(receipt.PlanFingerprint)
&& !string.IsNullOrWhiteSpace(receipt.ExecutionIrFingerprint)
&& receipt.ExecutedAtUtc <= DateTimeOffset.UtcNow;
}
| Ecosystem | Registry / Publisher | Published Artifacts |
|---|---|---|
| .NET 10 (C#) | NuGet (dero) |
Foundgine.Core, Foundgine.Runtime, Foundgine.Providers, Foundgine.Extensions, Foundgine.Aot |
| Java 27 | Maven Central (io.github.cristianbarragan) |
foundgine-core, foundgine-runtime, foundgine-providers, foundgine-extensions, foundgine-aot-generator |
| TypeScript / JS | npm (@foundgine) |
@foundgine/typescript, @foundgine/wasm |
| Python | PyPI | foundgine |
When an LLM agent (via Microsoft Agent Framework in .NET 10 or LangChain4j in Java 27) interacts with Foundgine over MCP, the boundary prevents prompt-injected guesses and unapproved writes through a deterministic multi-turn protocol:
| Turn | Agent / User Action | Foundgine Boundary Execution | Returned Structured Response |
|---|---|---|---|
| Turn 1 | Agent calls foundgine_discover |
Verifies host JWT/warrant and filters MetadataRegistry entities/fields visible to caller's role. |
Returns allowed entity schemas, weighted aliases, and relationship hops (sensitive fields omitted). |
| Turn 2 | Agent calls foundgine_query with "active customers" |
SemanticLexicalResolver detects 2 competing semantic signatures above threshold. |
Fails closed with RequiresClarification and lists both competing signatures for user disambiguation. |
| Turn 3 | User clarifies; Agent calls foundgine_query_semantic |
Authorizes graph traversal, injects tenant row predicate, lowers to parameterized SQL, records receipt. | Returns strictly authorized tenant rows + ExecutionReceipt provenance ID. |
| Turn 4 | Agent proposes order escalation via foundgine_mutate_dry_run |
Authorizes target entity/fields, simulates mutation graph, computes SHA-256 PlanFingerprint. |
Returns deterministic dry-run preview + PlanFingerprint (zero DB rows modified). |
| Turn 5 | Host governance signs fgmcp1; Agent calls foundgine_mutate_execute |
Verifies RSA-2048+ signature, exact PlanFingerprint match, consumes Redis jti nonce, commits tx. |
Commits business write + outbox event + durable audit receipt atomically. |
ExecutionIRCompiler and the dialect emitters (PostgresSqlDialect, SqliteSqlDialect, SqlServerSqlDialect) preserve identical semantic ordering, null handling, and parameterization across database engines:
| SQL Construct | PostgreSQL | SQLite | SQL Server (T-SQL) |
|---|---|---|---|
| Identifier Quoting | "schema"."table" |
"table" |
[schema].[table] |
| Parameter Syntax | @p_0 / $1 |
@p_0 |
@p_0 |
| Pagination & Tie-Breaker | ORDER BY ... , pk ASC LIMIT @take OFFSET @skip |
ORDER BY ... , pk ASC LIMIT @take OFFSET @skip |
ORDER BY ... , pk ASC OFFSET @skip ROWS FETCH NEXT @take ROWS ONLY |
| Case-Insensitive String Match | col ILIKE @pattern ESCAPE '\' |
LOWER(col) LIKE LOWER(@pattern) ESCAPE '\' |
LOWER(col) LIKE LOWER(@pattern) ESCAPE '\' |
| Outbox Concurrent Claiming | FOR UPDATE SKIP LOCKED |
Single-writer serialized transaction | WITH (UPDLOCK, READPAST, ROWLOCK) |
foundgine_warrant_revocation_anchor) and Redis—invalidating all active leaf warrants and delegation chains immediately.kid in JWKS/trust-roots and retiring the compromised kid.foundgine_audit_receipts by tenant_id, subject_id, or warrant_id to reconstruct every executed read/write, its contract_fp, plan_fp, and execution_ir_fp.correlation_id across foundgine_events and foundgine_outbox to trace downstream Temporal workflows and external side effects.
Time-dependent security invariants (warrant exp / nbf windows, fgmcp1 approval TTLs, outbox exponential retry backoff, and SSE session replay retention) are decoupled from system wall-clock time via injectable TimeProvider (.NET 10) and java.time.Clock (Java 27) abstractions:
+61s on a 60s activity warrant) to deterministically assert SecurityAuthorizationException without Thread.Sleep delays.AllowedClockSkew (default 30s) bounds NTP drift across distributed nodes without permitting expired replay windows.AnchoredSecurityWarrantRevocationStore to verify against PostgreSQL's durable GREATEST epoch anchor and deny ambiguous state.FailClosedOnAuditBackpressure = true aborts uncommitted mutations rather than silently dropping compliance receipts.Correct service lifetimes prevent accidental cross-request state leakage of caller identity or tenant predicates:
| Component | Recommended Lifetime | Thread-Safety & Isolation Guarantee |
|---|---|---|
MetadataRegistry |
Singleton | Deeply immutable after Build() / build(); lock-free concurrent reads across all threads. |
ISemanticAuthorizationPolicy |
Singleton (stateless) | Pure evaluation over SecurityExecutionContext and SemanticAuthorizationRequest; never caches per-user state on fields. |
SqlExecutionProvider / Plan Cache |
Singleton | Concurrent dictionary keyed by full SHA-256 SemanticPlanAuthorizationBinding digest + dialect. |
SecurityExecutionContext |
Per-Request / Scoped | Immutable record/class created fresh per HTTP/GraphQL/MCP call or Temporal activity; never stored in static fields. |
FoundgineEfReader / EntityManager |
Scoped (Per-Unit-of-Work) | Bound to the active request/transaction unit-of-work; disposed cleanly at request completion. |
MetadataRegistry contract fingerprints and SQL plan caches are deterministic, regional nodes compute identical digests independently without cross-region coordination.foundgine_outbox entries, and foundgine_audit_receipts in one local ACID transaction; outbox workers replicate downstream events idempotently via idempotency_key.TTL ≤ 5m) bounds exposure during cross-region revocation replication windows.
Because MetadataRegistry computes a deterministic SHA-256 ContractFingerprint at freeze time and binds that digest into active warrants and dry-run mutation approvals, rolling deployments follow a strict Expand → Migrate → Contract lifecycle to eliminate PlanBindingTamperedException errors during canary rollouts:
| Rollout Phase | Database & Model Change | Warrant & Approval Behavior |
|---|---|---|
| 1. Expand (Additive) | Add nullable columns or new tables in PostgreSQL; register new entities, fields, and weighted aliases in FoundgineModel. |
Existing read queries continue uninterrupted; plan caches automatically partition by the new ContractFingerprint. |
| 2. Dual-Version Canary Drain | Route traffic across vN and vN+1 pods; issue short-lived dry-run approvals (TTL ≤ 60s) pinned to the serving node's contract version. |
If an approval created on vN lands on vN+1, PlanBindingTamperedException fails closed cleanly and triggers an immediate client dry-run refresh. |
| 3. Contract (Deprecation) | Remove deprecated aliases/fields from FoundgineModel only after 100% of nodes run vN+1, then drop legacy physical columns. |
Compile-time AOT source generators validate zero dangling references at build time before deployment. |
Offset pagination (OFFSET N) degrades linearly on large tables and skips or duplicates rows when concurrent writes occur. Foundgine's cursor pagination compiles CursorSliceNode into parameterized lexicographic tuple comparisons anchored by the entity's primary key tie-breaker:
// Deterministic ordering: Total DESC, Id ASC (primary key tie-breaker injected automatically)
var page1 = await executor.ExecuteAsync(
SemanticQuery.From(metadata, "SalesOrder")
.Select("Id", "OrderNumber", "Total")
.OrderByDesc("Total")
.Take(50)
.Build(),
hostContext, ct);
// Resume deterministically from page1.NextCursor without OFFSET drift
var page2 = await executor.ExecuteAsync(
SemanticQuery.From(metadata, "SalesOrder")
.Select("Id", "OrderNumber", "Total")
.OrderByDesc("Total")
.AfterCursor(page1.NextCursor!)
.Take(50)
.Build(),
hostContext, ct);
-- Cursor encodes { "sort": [2450.00, "0193a8f1-..."], "dir": ["DESC", "ASC"], "fp": "sha256:..." }
-- Cursor fingerprint is verified against the active query shape before binding!
SELECT o.ord_id, o.ord_number, o.ord_total
FROM erp.tbl_order o
WHERE o.tenant_id = @p_auth_tenant
AND (
o.ord_total < @p_cursor_0
OR (o.ord_total = @p_cursor_0 AND o.ord_id > @p_cursor_1)
)
ORDER BY o.ord_total DESC, o.ord_id ASC
LIMIT @p_take;
| Workspace Root | Entry Manifest | Automated Verification Gate |
|---|---|---|
src/csharp/ |
Foundgine.sln |
Unit, SQL/EF Core integration, Roslyn AOT parity, RedTeam (18 vectors), and PenTest (14 vectors). |
src/java/ |
pom.xml |
JUnit 5 core/runtime/JPA/MCP/GraphQL/Keycloak/Temporal suites + annotation processor AOT parity. |
src/conformance/ |
*.json vectors |
Cross-language semantic query, lexical grounding, and structural resource-limit equivalence checks. |
src/typescript/ |
package.json |
TypeScript strict typecheck + MCP client & Temporal workflow runner tests. |
src/python/ |
pyproject.toml |
pytest async MCP transport, clarification handling, and error taxonomy tests. |
src/wasm/ |
Cargo.toml |
cargo test & wasm-bindgen parity checks against TypeScript/Python SDK contracts. |
Domain-driven codebases wrap primitives in strongly typed value objects (OrderId, TenantSlug, IsoCurrencyCode). ISemanticValueConverter<TDomain, TCanonical> (.NET 10) and SemanticValueConverter<D, C> (Java 27) translate domain value objects at the boundary so ExecutionIR and SQL parameter binders operate strictly on validated canonical scalars:
using Foundgine.Core.Metadata;
public readonly record struct OrderId(Guid Value);
public sealed class OrderIdConverter : ISemanticValueConverter<OrderId, Guid>
{
public Guid ToCanonical(OrderId domainValue) => domainValue.Value;
public OrderId FromCanonical(Guid canonicalValue) => new(canonicalValue);
}
// Registered once in FoundgineModel:
// entity.Property(x => x.Id).HasColumn("ord_id").HasConverter<OrderIdConverter>();
Eq(field, null) is rejected at validation time; callers must use explicit IsNull(field) or IsNotNull(field) operators, which compile to IS NULL / IS NOT NULL.In(...) Sets: An empty collection passed to WhereIn(field, []) compiles deterministically to a false predicate (1 = 0) rather than invalid SQL IN () syntax.LIKE Wildcard Escaping: User-supplied strings in Contains, StartsWith, and EndsWith automatically escape %, _, and \ before parameter binding.
For regulated data exports, ledger reconciliation, and large batch inspections where buffering 100,000+ rows in heap memory would risk GC pauses or OOM kills, IFoundgineStreamingExecutor (.NET 10 IAsyncEnumerable<T>) and FoundgineStreamExecutor (Java 27 Stream<T>) stream rows over server-side forward-only database cursors under the exact same authorization and receipt guarantees:
// Streams rows with constant O(1) fetch-buffer memory while enforcing tenant/column policy.
// ExecutionReceipt is finalized and flushed to BufferedDurableAuditLog upon stream completion or cancellation.
await foreach (var row in streamingExecutor.StreamAsync(exportQuery, hostContext, ct))
{
await ndjsonWriter.WriteRowAsync(row, ct);
}
| ADR ID & Title | Architectural Decision | Trade-Off Accepted |
|---|---|---|
| ADR-001 · Frozen Semantic Contract | Freeze MetadataRegistry at startup with an immutable SHA-256 fingerprint rather than mutating schema metadata dynamically per request. |
Schema updates require a rolling deployment or explicit registry reload, in exchange for lock-free concurrency and tamper-proof plan binding. |
| ADR-002 · Non-Authoritative Retrieval | Forbid BM25, vector, and graph retrieval adapters from executing queries or resolving ambiguity autonomously. | Ambiguous prompts require an extra clarification round-trip (RequiresClarification), eliminating silent misinterpretation of user intent. |
| ADR-003 · Host-Owned Security Context | Require host middleware/adapters to construct SecurityExecutionContext exclusively from verified tokens/warrants. |
Transport adapters cannot accept convenience tenantId query parameters, guaranteeing immunity to payload identity spoofing. |
| ADR-004 · Two-Phase Signed Mutations | Separate mutation dry-run planning from execution via a host-signed fgmcp1 token bound to the SHA-256 PlanFingerprint. |
Writes require a dry-run preview step, preventing unapproved or drifted LLM/client mutations from reaching storage. |
| ADR-005 · Algebraic ExecutionIR Boundary | Lower logical plans into a closed ExecutionIR AST rather than passing raw SQL strings or unvalidated ORM expressions to providers. |
New storage backends implement a small algebraic translator, ensuring uniform predicate pushdown and plan-cache isolation across SQL, EF Core, and JPA. |
Domain models frequently expose calculated attributes—such as LineTotal (Quantity * UnitPrice), IsOverdue (DueDate < CurrentUtc && Status != "PAID"), or DisplayLabel—that do not correspond 1:1 to a single physical column. FoundgineModel allows declaring read-only computed semantic fields using a closed, deterministic expression AST that lowers cleanly into SQL across PostgreSQL, SQLite, and SQL Server:
// Declare a read-only derived field in FoundgineModel:
entity.ComputedProperty("LineTotal", SemanticType.Decimal, expr =>
expr.Multiply(expr.Field("Quantity"), expr.Field("UnitPrice")));
// Policy benefit: A caller can be granted read access to 'LineTotal'
// while raw 'UnitPrice' or 'UnitCost' remains denied at the field projection gate!
var query = SemanticQuery.From(metadata, "PurchaseOrderLine")
.Select("Sku", "Quantity", "LineTotal")
.WhereGt("LineTotal", 500.00m)
.Build();
SELECT l.sku,
l.qty,
(l.qty * l.unit_price) AS "LineTotal"
FROM erp.tbl_po_line l
WHERE l.tenant_id = @p_auth_tenant
AND (l.qty * l.unit_price) > @p_0
ORDER BY l.po_line_id ASC
LIMIT @p_take;
Manufacturing Bill-of-Materials (BOM), organizational reporting trees, and nested category graphs require bounded self-referential traversal. Foundgine compiles bounded hierarchical includes into parameterized WITH RECURSIVE common table expressions while enforcing SecurityResourceLimits.MaxSelectionDepth and injecting mandatory tenant predicates into both the anchor and recursive terms:
WITH RECURSIVE bom_tree AS (
-- Anchor member (depth = 1) with mandatory tenant predicate
SELECT p.part_id, p.parent_part_id, p.sku, 1 AS depth
FROM erp.tbl_part p
WHERE p.tenant_id = @p_auth_tenant
AND p.part_id = @p_root_id
UNION ALL
-- Recursive member bounded by SecurityResourceLimits & tenant predicate at every hop
SELECT c.part_id, c.parent_part_id, c.sku, t.depth + 1
FROM erp.tbl_part c
INNER JOIN bom_tree t ON c.parent_part_id = t.part_id
WHERE c.tenant_id = @p_auth_tenant
AND t.depth < @p_max_depth
)
SELECT part_id, parent_part_id, sku, depth
FROM bom_tree
ORDER BY depth ASC, part_id ASC;
For full-stack verification in CI without shared staging environments, Foundgine's integration suites spin up ephemeral PostgreSQL, Redis, and Keycloak containers via Testcontainers to validate real OIDC JWT verification, Redis Lua + PostgreSQL anchor revocation, SQL lowering, and transactional outbox delivery:
@Testcontainers
class AnchoredRevocationIntegrationTest {
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:17-alpine");
@Container
static GenericContainer<?> redis = new GenericContainer<>("redis:7-alpine").withExposedPorts(6379);
@Test
void advancingPostgresAnchorEpoch_BlocksStaleWarrantsEvenIfRedisFlushes() {
var store = AnchoredRevocationFactory.create(
postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword(),
redis.getHost(), redis.getMappedPort(6379));
store.advanceIssuerEpoch("https://auth.acme.example", 42L);
redis.execInContainer("redis-cli", "FLUSHALL"); // Simulate cold Redis failover
var decision = store.verifyAndConsume("https://auth.acme.example", "warrant-1", "jti-99", 41L, 300);
assertFalse(decision.isAllowed());
assertEquals("EPOCH_SUPERSEDED", decision.rejectionCode());
}
}
Reporting dashboards and operational summaries require grouped aggregates (Count, Sum, Avg, Min, Max) without sacrificing row-level tenant isolation or exposing restricted columns. Foundgine lowers SemanticAggregateQuery into parameterized GROUP BY / HAVING SQL where mandatory authorization predicates execute in the pre-aggregation WHERE clause:
// Policy verifies caller has read access to SalesOrder.Status and SalesOrder.Total
// and injects TenantId == @p_auth_tenant into the pre-aggregation WHERE clause.
var summaryQuery = SemanticAggregateQuery.From(metadata, "SalesOrder")
.GroupBy("Status")
.SelectCount("OrderCount")
.SelectSum("Total", alias: "TotalRevenue")
.HavingGt("TotalRevenue", 10000.00m)
.OrderByDesc("TotalRevenue")
.Build();
SELECT o.status AS "Status",
COUNT(*) AS "OrderCount",
SUM(o.ord_total) AS "TotalRevenue"
FROM erp.tbl_order o
WHERE o.tenant_id = @p_auth_tenant
GROUP BY o.status
HAVING SUM(o.ord_total) > @p_having_0
ORDER BY "TotalRevenue" DESC, o.status ASC;
Foundgine.Providers.Aot.Generator (C# Roslyn incremental source generator) and foundgine-aot-generator (Java 27 JSR-269 annotation processor) validate domain annotations at compile time and emit reflection-free metadata builders that produce byte-for-byte identical ContractFingerprint digests to runtime fluent models:
| Diagnostic ID | Severity | Compile-Time Check & Remediation |
|---|---|---|
FG001 |
Error | [FoundgineEntity] / @FoundgineEntity lacks a declared primary key ([FoundgineKey]); add a key property before building. |
FG002 |
Error | Duplicate entity name, physical table collision, or duplicate weighted alias declared across entities in the same model. |
FG003 |
Error | [FoundgineRelationship] references an undeclared target entity or mismatched foreign-key scalar type. |
FG004 |
Error | Alias weight outside valid inclusive range 1..100; adjust weight to a deterministic integer bound. |
FG005 |
Info | Emits deterministic GeneratedFoundgineMetadata builder and verifies zero reflection fallback paths for Native AOT / GraalVM. |
| Release Gate | Verification Command / Artifact | Pass Criterion |
|---|---|---|
| 1. Cross-Language Conformance | src/conformance/*.json across .NET 10 & Java 27 |
100% identical ASTs, contract fingerprints, and grounding/limit outcomes. |
| 2. Adversarial Red-Team & PenTest | Foundgine.RedTeam + SupplyChain.PenTest |
32/32 adversarial probes fail closed with zero cross-tenant or unapproved writes. |
| 3. Native AOT & Zero-Reflection | dotnet publish -p:PublishAot=true + Maven AP build |
Zero trim/AOT warnings; SES-018 fingerprint matches fluent runtime builder. |
| 4. Docs, SEO & Discovery Sync | docs-site/foundgine-overview.html, sitemap.xml, robots.txt, llms.txt |
Valid XML sitemap, canonical URLs, Schema.org JSON-LD, and synchronized repo index. |
Network timeouts between an MCP client, Temporal worker, or API gateway and the database can cause callers to retry a mutation whose initial commit already succeeded. Foundgine enforces deterministic idempotency across both synchronous mutations and asynchronous outbox dispatch:
fgmcp1 Nonce + Idempotency Keyfgmcp1 approval carries a unique jti nonce consumed atomically in Redis/PostgreSQL on first execution; blind replays fail closed with WarrantReplayDetectedException.IdempotencyKey (e.g., order-req-98412) stored in the same ACID transaction so idempotent retries return the original committed ExecutionReceipt without re-executing side effects.foundgine_outbox.idempotency_key carries a UNIQUE database constraint derived from (tenant_id, receipt_id, topic, step_index).
In addition to binary column allow/deny pruning, SemanticAuthorizationDecision supports declarative field redaction transforms (MaskLast4, RedactEmail, Nullify) applied deterministically before rows leave the execution boundary:
// Support agents can inspect Customer records and verify the last 4 digits of TaxId,
// while full TaxId values remain accessible only to 'compliance-officer' principals.
var decision = SemanticAuthorizationDecision.Allow(
allowedFields: ["Id", "Name", "Email", "TaxId"],
rowPredicate: SemanticFilter.Eq("TenantId", ctx.TenantId),
fieldTransforms: new Dictionary<string, FieldRedactionMode>
{
["TaxId"] = ctx.Roles.Contains("compliance-officer")
? FieldRedactionMode.None
: FieldRedactionMode.MaskLast4,
["Email"] = ctx.Roles.Contains("compliance-officer")
? FieldRedactionMode.None
: FieldRedactionMode.MaskLocalPart
});
| Deployment Profile | Cold Start | Idle RSS Memory | Metadata Initialization |
|---|---|---|---|
.NET 10 Native AOT (PublishAot=true + Roslyn Generator) |
~15 – 25 ms | ~28 – 42 MB | Zero reflection; compile-time static metadata graph. |
| .NET 10 Server JIT (Chiseled Container) | ~85 – 140 ms | ~65 – 95 MB | Single startup freeze of MetadataRegistry; dynamic PGO warm-up. |
Java 27 HotSpot JVM (foundgine-aot-generator) |
~280 – 450 ms | ~140 – 210 MB | Annotation-processor generated builder; zero runtime reflection. |
HTTP, GraphQL, and MCP transport adapters translate internal Foundgine rejections into deterministic, non-leaky error envelopes (application/problem+json per RFC 9457 over HTTP, and structured JSON-RPC 2.0 error objects over /mcp) so clients never receive raw stack traces or database schema leaks:
| Problem Type URN | HTTP Status | Retryable? | Diagnostic Extension Fields |
|---|---|---|---|
urn:foundgine:problem:clarification-required |
422 Unprocessable Content |
Only after user disambiguation | competingSignatures[], tokensExplored, pathsExplored |
urn:foundgine:problem:authorization-denied |
403 Forbidden |
No (fail-closed) | contractFingerprint, correlationId (never leaks restricted field names) |
urn:foundgine:problem:warrant-replay-or-revoked |
403 Forbidden |
No (mint fresh warrant/approval) | rejectionCode (REPLAY_DETECTED, WARRANT_REVOKED, EPOCH_SUPERSEDED) |
urn:foundgine:problem:plan-binding-drift |
409 Conflict |
Re-run dry-run & re-approve | expectedContractFingerprint, actualContractFingerprint |
urn:foundgine:problem:resource-limit-exceeded |
400 Bad Request |
No (reduce depth/nodes/page size) | limitKind (MaxSelectionDepth, MaxNodes, MaxPageSize), limitValue |
When applications pair Foundgine with approximate candidate retrieval (ParadeDB BM25, PostgreSQL pg_trgm, pgvector, or Apache AGE), domain catalog updates flow out of foundgine_outbox or PostgreSQL logical replication slots to update search indexes asynchronously:
SemanticLexicalResolver validates every candidate against the frozen MetadataRegistry and enforces current SQL-lowered row/column policies at execution time.| SDK Package | Transport & Serialization Engine | Key Runtime Guarantees |
|---|---|---|
@foundgine/typescript |
Fetch / HTTP/2 + SSE parser + strict TypeScript discriminated unions | Zero runtime dependencies; native AbortSignal cancellation and automatic Last-Event-ID stream resumption. |
foundgine (PyPI) |
httpx async/sync client + typed dataclasses / Pydantic-compatible models |
Supports both async with AsyncFoundgineClient(...) and synchronous workflows with structured clarification objects. |
@foundgine/wasm |
Rust serde_json + wasm-bindgen WebAssembly core |
Identical JSON-RPC framing, retry backoff, and Temporal workflow helpers compiled to browser and edge-worker Wasm modules. |
In microservice and federated architectures, independent bounded contexts (such as Orders, Inventory, and Billing) each maintain their own frozen MetadataRegistry and isolated database while honoring a single end-to-end user identity and tenant boundary:
MetadataRegistry, preventing monolithic schema coupling across teams./graphql or /mcp endpoint while forwarding the caller's verified bearer token or attenuated child warrant.user:alice in tenant-alpha, it mints an attenuated child warrant scoped strictly to InventoryLot read operations with a 30-second TTL.tenant-alpha predicate.
Rather than writing monolithic conditional branches inside a single authorization class, teams compose small, unit-testable policy rules using Foundgine's deterministic policy combinators (CompositeAuthorizationPolicy.AllOf(...)). Conjunction combines row-level predicates via logical AND and intersects allowed field projections:
using Foundgine.Runtime.Authorization;
// Combine independent, single-responsibility authorization policies:
// 1. TenantIsolationPolicy -> injects TenantId == ctx.TenantId
// 2. RegionFencingPolicy -> injects RegionCode IN ctx.AllowedRegions
// 3. FinanceFieldGatePolicy -> intersects AllowedFields, stripping UnitCost unless role == "finance"
var composedPolicy = CompositeAuthorizationPolicy.AllOf(
new TenantIsolationPolicy(),
new RegionFencingPolicy(),
new FinanceFieldGatePolicy());
// Result:
// - RowPredicate = (TenantId == @p_tenant) AND (RegionCode IN (@p_reg_0, @p_reg_1))
// - AllowedFields = Intersection of all three policies' allowed field sets (fails closed if empty)
| Subsystem Resource | Recommended Sizing Formula | Operational Rationale |
|---|---|---|
PostgreSQL Pool (MaxPoolSize / HikariCP) |
(CPU_cores * 2) + effective_spindle_count (typically 16–32 per pod) |
Prevents PostgreSQL lock contention and context-switch thrashing under high concurrency (c=32+) while keeping warm plan-cache queries sub-15 ms. |
BufferedDurableAuditLog Ring Buffer |
Peak_Write_RPS * Max_Flush_Latency_Sec * 4 (e.g., 8,192 slots) |
Absorbs transient PostgreSQL commit spikes without blocking writers; triggers fail-closed backpressure only if durable persistence stalls completely. |
| Outbox Worker Concurrency | 2–4 concurrent FOR UPDATE SKIP LOCKED workers per replica, batch size 64 |
Sustains >2,500 outbox dispatches/sec per pod with negligible lock contention on ix_foundgine_outbox_pending. |
| Plan Cache Capacity | Distinct_Shapes * Distinct_Role_Predicate_Signatures (typically < 2,000 entries) |
Bounded LRU/concurrent map (~15–30 MB RAM) guarantees >99.5% warm SQL template hit rate in steady state. |
Enterprise entities (such as PurchaseOrder, ShipmentManifest, or ComplianceCertificate) frequently reference binary documents (PDF invoices, signed manifests, CAD drawings). Rather than streaming multi-megabyte blobs through ExecutionIR or LLM tool payloads, Foundgine stores immutable SHA-256 content digests and object keys in relational columns and mints short-lived, scope-bound pre-signed URIs only after row-level and field-level policy authorization succeeds:
SHA-256 content digest before commit; the digest and object key are written inside the same ACID mutation transaction as the parent business record.DownloadUri field, a post-authorization projection hook mints a 60s read-only S3 / Azure Blob / GCS URL bound to the verified TenantId and records the access in ExecutionReceipt.
To protect downstream databases and lexical candidate sources from noisy-neighbor tenants or runaway agent loops, Foundgine pairs structural SecurityResourceLimits with multi-tier sliding-window token-bucket quotas evaluated immediately after host context verification:
| Quota Dimension | Keying Granularity | Rejected Response |
|---|---|---|
| Read Execution Quota | (TenantId, SubjectId) sliding window |
429 Too Many Requests + Retry-After header + urn:foundgine:problem:quota-exceeded |
| Lexical Grounding Budget | (TenantId, GroundingCallsPerMin) + LexicalBudget |
Caps BM25 / pgvector / Apache AGE retrieval fan-out before database saturation. |
| Mutation & Dry-Run Quota | (TenantId, WriteOpsPerMin) |
Prevents runaway agent mutation proposal loops from flooding approval stores or outbox tables. |
Foundgine.Core + Foundgine.Runtime (.NET 10) or foundgine-core + foundgine-runtime (Java 27).FoundgineModel subclass and freeze MetadataRegistry as a singleton.ISemanticAuthorizationPolicy / SemanticAuthorizationPolicy returning mandatory tenant row predicates and column allowlists.InMemoryExecutionProvider.DbContext / JPA EntityManagerFactory./graphql and/or /mcp behind host OIDC/Keycloak authentication and inspect ExecutionReceipt logs.
Beyond structural schema types and row-level authorization, enterprise writes enforce domain invariants (such as Quantity > 0, ShipDate >= OrderDate, or external credit-limit checks) before any database transaction commits. Foundgine evaluates both declarative property constraints from MetadataRegistry and async domain validators (ISemanticMutationValidator / SemanticMutationValidator) during DryRunAsync and re-verifies them inside ExecuteApprovedAsync:
using Foundgine.Runtime.Mutations;
public sealed class PurchaseOrderInvariantValidator : ISemanticMutationValidator
{
public ValueTask<MutationValidationResult> ValidateAsync(
MutationValidationContext context,
CancellationToken ct)
{
if (context.TargetEntity != "PurchaseOrder")
return ValueTask.FromResult(MutationValidationResult.Valid());
if (context.TryGetDecimal("Total", out var total) && total <= 0m)
return ValueTask.FromResult(
MutationValidationResult.Invalid("Total", "Order total must be strictly positive."));
return ValueTask.FromResult(MutationValidationResult.Valid());
}
}
When read queries are offloaded to asynchronous PostgreSQL read replicas, a user or agent reading immediately after committing a mutation could observe stale replica state unless causal ordering is preserved:
MutationExecutionResult and ExecutionReceipt record the committed PostgreSQL Write-Ahead Log position (pg_current_wal_insert_lsn()) or monotonic stream version.pg_last_wal_replay_lsn() on replicas and automatically routes the query to the primary node until replicas catch up—preserving full tenant/column authorization transparently.| Observed Symptom | Root Cause | Deterministic Resolution |
|---|---|---|
PlanBindingTamperedException on ExecuteApprovedAsync |
Dry-run approval was minted against an older pod's ContractFingerprint during a rolling deploy, or payload fields were altered post-dry-run. |
Ensure MetadataRegistry is frozen identically across replicas; have client re-run DryRunAsync and obtain a fresh approval. |
Frequent GroundingOutcome.RequiresClarification on known terms |
Two entities declare overlapping aliases with equal weights, or MinimumAliasWeight is set higher than candidate scores. |
Disambiguate alias weights in FoundgineModel (e.g., 95 vs 60) or use structured SemanticQuery / foundgine_query_semantic. |
403 Forbidden despite valid JWT authentication |
ISemanticAuthorizationPolicy pruned all requested fields (empty projection set) or caller lacked an intermediate traversal hop permission. |
Inspect foundgine.security.denials_total tags and verify role permissions across every entity hop in SemanticOperationGraph. |
EPOCH_SUPERSEDED after Redis restart |
Expected fail-closed protection: PostgreSQL's foundgine_warrant_revocation_anchor holds a higher monotonic epoch than the warrant's rev_seq. |
Mint a fresh warrant from the trusted root issuer reflecting the current revocation epoch. |
Long-lived enterprise platforms must rotate signing keys on schedule and respond to key compromise without breaking in-flight requests or invalidating historical compliance evidence:
kid Rollover for Warrants & fgmcp1 Approvalskid) via JWKS or KMS key rings.kid is added to verifiers before issuers switch signing to the new key, ensuring zero dropped validations while retaining instant single-kid revocation on compromise.ExecutionIR query semantics.
While Foundgine ships built-in providers for PostgreSQL, SQLite, SQL Server, EF Core, JPA/Hibernate, and InMemory testing, teams can bind bespoke datastores (such as ClickHouse, DuckDB, or internal RPC data services) by implementing IExecutionProvider (.NET 10) or ExecutionProvider (Java 27). Every custom provider must verify the SemanticPlanAuthorizationBinding proof before lowering ExecutionIR:
using Foundgine.Core.Execution;
public sealed class CustomAnalyticsExecutionProvider : IExecutionProvider
{
public async ValueTask<ExecutionResult> ExecuteAsync(
BoundExecutionPlan boundPlan,
CancellationToken ct)
{
// 1. Mandatory fail-closed gate: reject any IR lacking a valid authorization binding proof
boundPlan.EnsureAuthorizedAndBound();
// 2. Translate closed ExecutionIR AST (Scan, Filter, Join, Project, Sort, Slice)
// including all policy-injected row predicates and pruned field projections
var translated = AnalyticsDialectLowerer.Lower(boundPlan.Ir);
var rows = await ExecuteParameterisedAsync(translated, ct);
return new ExecutionResult(rows, boundPlan.Binding.PlanFingerprint);
}
}
| Domain | Production Requirement | Verification Evidence |
|---|---|---|
| Identity & Transport | Strict OIDC issuer/audience validation; explicit AllowedOrigins on /mcp; zero payload-derived identity claims. |
Integration tests rejecting untrusted Origin, wrong aud, and spoofed TenantId arguments. |
| Semantic Contract | MetadataRegistry frozen once at startup; identical ContractFingerprint across all active pods. |
Startup readiness probe asserting expected contract digest and zero AOT drift (SES-018). |
| Authorization & Writes | Mandatory row predicates lowered to SQL; dry-run PlanFingerprint + host-signed fgmcp1 required for all mutations. |
32/32 passing adversarial vectors in Foundgine.RedTeam and SupplyChain.PenTest. |
| Revocation & Audit | Redis Lua + PostgreSQL GREATEST revocation anchor active; FailClosedOnAuditBackpressure = true. |
Chaos test confirming stale warrants fail closed after Redis flush and audit receipts persist atomically. |
When PostgresOutboxWorker dispatches committed domain events to external webhooks, partner APIs, or cross-cluster event buses, each outbound payload carries cryptographic authenticity and replay-prevention headers derived from the persisted foundgine_outbox record:
"{timestamp}.{eventId}.{canonicalJsonBody}" using constant-time comparison and reject timestamps outside a 300s tolerance window.receiptId and contractFingerprint so downstream services can trace every asynchronous side effect back to its originating ExecutionReceipt.
In federated GraphQL gateways (Hot Chocolate Fusion, Apollo Router, or GraphQL Java Federation), Foundgine projects frozen MetadataRegistry entities into federated subgraphs with explicit @key entity resolvers and role-gated query roots:
builder.Services.AddFoundgineGraphQL(gql =>
{
// Enforce explicit role allowlists per exposed GraphQL root entity
gql.QueryRootRoles["SalesOrder"] = ["sales", "finance", "support"];
gql.QueryRootRoles["Customer"] = ["sales", "support"];
// Enable @key entity reference resolution for GraphQL Federation gateways;
// Reference resolvers still execute through FoundgineGraphQLQueryExecutor
// with mandatory host-verified SecurityExecutionContext!
gql.EnableFederationReferenceResolvers = true;
gql.MaxSelectionDepth = 12;
});
Run this unified verification script before tagging any Foundgine release to validate .NET 10, Java 27, TypeScript, Python, Rust/WASM, and SEO/Documentation assets in one deterministic pass:
#!/usr/bin/env bash
set -euo pipefail
# 1. .NET 10 Release Test Suite & Native AOT Publish Check
dotnet test src/csharp/Foundgine.sln -c Release
dotnet publish src/csharp/samples/Foundgine.SupplyChain -c Release -p:PublishAot=true
# 2. Java 27 Maven Reactor Build & Conformance / Security Verification
mvn -f src/java/pom.xml -B verify
# 3. Client SDKs (TypeScript, Python, Rust/WASM)
npm --prefix src/typescript ci && npm --prefix src/typescript test
pytest src/python/tests
cargo test --manifest-path src/wasm/Cargo.toml
# 4. Validate Documentation Sitemap XML & Robots.txt Integrity
xmllint --noout docs-site/sitemap.xml
grep -q "Sitemap: https://cristianbarragan.github.io/foundgine/sitemap.xml" docs-site/robots.txt
echo "All Foundgine v3.4.2 release gates passed."
Foundgine instruments every boundary transition using W3C traceparent / tracestate propagation and deterministic ActivitySource("Foundgine") spans without leaking sensitive parameter values or restricted field names into telemetry attributes:
| Span / Metric Name | Kind | Safe Cardinality Attributes |
|---|---|---|
foundgine.semantic.resolve |
Span | foundgine.contract.fingerprint, foundgine.grounding.outcome, foundgine.grounding.paths_explored |
foundgine.security.authorize |
Span | foundgine.entity, foundgine.operation.kind, foundgine.auth.decision |
foundgine.execution.ir_run |
Span | foundgine.provider (postgres, efcore, jpa), foundgine.plan.cache_hit, foundgine.rows.returned |
foundgine.security.denials_total |
Counter | foundgine.denial.category (tenant, field, warrant, replay, limit) |
Regulated enterprise domains require logical soft-deletion (DeletedAtUtc IS NULL) during active retention windows alongside verifiable erasure under GDPR / CCPA right-to-erasure mandates:
.HasSoftDelete("deleted_at_utc") automatically inject deleted_at_utc IS NULL into every standard read query and relationship join unless a principal holds explicit IncludeDeleted policy authority.Delete mutations on soft-deletable entities lower into parameterized UPDATE ... SET deleted_at_utc = @now statements while recording full ExecutionReceipt provenance.
For globally distributed deployments accepting writes in multiple regions, Foundgine pairs optimistic concurrency tokens (RowVersion / xmin) with deterministic conflict resolution policies declared per entity:
ConcurrencyConflictException (409 Conflict) so callers re-read authoritative state before retrying.DRAFT → SUBMITTED → APPROVED → SHIPPED), rejecting out-of-order regressions automatically during regional reconciliation.
Long-running multi-system processes (such as order fulfillment, credit reservation, and warehouse dispatch) use Foundgine.Extensions.Temporal (.NET 10) or com.foundgine.extensions.temporal (Java 27) to combine Temporal's deterministic workflow replay with Foundgine's short-lived activity warrants:
SemanticOperation / SemanticMutationIntent ASTs and forwards workflow-propagated identity headers—never performing direct database I/O or non-deterministic clock reads.TTL ≤ 60s), executes the dry-run/signed mutation inside an ACID database transaction, and returns the immutable ExecutionReceipt ID as the activity result.ExecutionReceipt correlation IDs.
Alongside the core MCP tools (foundgine_discover, foundgine_query, foundgine_query_semantic, foundgine_mutate_dry_run, foundgine_mutate_execute), hosts can expose read-only MCP resources and parameterized prompt templates over /mcp—all gated by the caller's verified SecurityExecutionContext:
| MCP Surface | URI / Identifier | Security & Boundary Enforcement |
|---|---|---|
| Resource | foundgine://schema/authorized-catalog |
Returns only entities, relationships, and fields permitted for the caller's verified roles (restricted fields omitted). |
| Resource | foundgine://audit/receipts/{receiptId} |
Enforces tenant_id == ctx.TenantId before returning provenance digests so tenants cannot inspect peer receipts. |
| Prompt | reconcile-overdue-invoices |
Injects structured disambiguation hints and tenant-scoped filter parameters without bypassing RequiresClarification gates. |
Because Foundgine systematically injects tenant_id = @p_auth_tenant predicates and appends , pk ASC tie-breakers to every sorted query, aligning PostgreSQL composite indexes with these patterns yields single-index-scan execution plans:
-- 1. Covering composite B-tree for tenant-scoped keyset pagination (Total DESC, Id ASC):
CREATE INDEX CONCURRENTLY ix_orders_tenant_total_id
ON erp.tbl_order (tenant_id, ord_total DESC, ord_id ASC)
INCLUDE (ord_number, ord_status)
WHERE deleted_at_utc IS NULL;
-- 2. Partial index for FOR UPDATE SKIP LOCKED outbox workers:
CREATE INDEX CONCURRENTLY ix_foundgine_outbox_ready
ON foundgine_outbox (next_attempt_at_utc, created_at_utc)
WHERE status = 'PENDING';
High-throughput ingestion jobs, catalog imports, and scheduled reconciliations often submit hundreds or thousands of mutations rather than a single row write. Foundgine governs bulk operations through explicit chunk sizing, per-chunk dry-run authorization, and configurable atomicity policies:
AtomicityMode.StrictAllOrNothing): Executes all items in the mutation graph inside a single database transaction; if any item fails policy, invariant validation, or optimistic concurrency, the entire batch rolls back.ChunkSize = N): Splits large mutation sets into fixed-size transactional chunks (e.g., 250 items per commit) so lock durations stay bounded and partial progress is recorded with per-chunk ExecutionReceipt IDs.In zero-trust Kubernetes or service-mesh environments (Envoy, Istio, Linkerd with SPIFFE/SPIRE workload identities), network transport authentication and semantic execution authority reinforce one another without conflating workload identity with end-user or delegated agent authority:
| Security Layer | Mechanism | Role in Foundgine Defense-in-Depth |
|---|---|---|
| Transport Identity | SPIFFE SVIDs (spiffe://...) over mTLS |
Authenticates pod-to-pod and gateway-to-service channels at the network edge. |
| Caller & Tenant Context | Verified OIDC / Keycloak JWT + Host Context | Establishes immutable SubjectId, TenantId, Roles, and DelegationChain—never inferred from raw network IP or spoofable headers. |
| Action & Plan Binding | Cryptographic Warrants + fgmcp1 + PlanFingerprint |
Binds high-impact writes and delegated sub-calls to exact operations, TTLs, and SHA-256 plan digests. |
Because Foundgine enforces authorization, row-level predicate lowering, signed mutation approval, and immutable receipt recording at architectural boundaries rather than ad-hoc application code, engineering teams can map runtime primitives directly to compliance controls:
| Compliance Concern | Foundgine Control Mechanism | Audit Artifact / Evidence |
|---|---|---|
| Least Privilege & Access Control | Role- and policy-gated field projections + fail-closed grounding (RequiresClarification). |
SemanticAuthorizationDecision + foundgine.security.denials_total |
| Tenant & Data Segregation | Mandatory host-verified row predicates lowered into parameterized SQL WHERE / WITH RECURSIVE. |
ExecutionIR + ExecutionIrFingerprint in foundgine_audit_receipts |
| Change & Write Integrity | Two-phase dry-run (PlanFingerprint) + host-signed fgmcp1 + atomic outbox commit. |
Signed approval provenance + foundgine_outbox & foundgine_audit_receipts |
| Data Erasure & Retention | Soft-delete predicates (deleted_at_utc) + tenant/subject DEK crypto-shredding. |
KMS key-destruction event + preserved non-PII receipt ledger |
Teams adopt Foundgine incrementally without rewriting existing databases, ORMs, or API gateways. Below are the three standard adoption paths, answers to common architectural questions, and a complete HTML site map of all documentation and machine-readable artifacts.
DbContext / EntityManager and PostgreSQL/SQL Server/SQLite schema untouched.FoundgineModel mapping your business entities and legacy table/column names.FoundgineEfReader or JpaEntities so tenant and role predicates enforce uniformly in SQL.MapFoundgineGraphQL (/graphql) with explicit QueryRootRoles allowlists./mcp alongside GraphQL—reusing the exact same MetadataRegistry, warrant verification, and row-level predicates in ~15 lines of wiring.[FoundgineEntity] (.NET) or @FoundgineModel (Java).Foundgine.Providers.Aot.Generator or FoundgineAotProcessor emit compile-time metadata builders with zero runtime reflection.No. Foundgine complements them. Hot Chocolate and GraphQL Java act as thin transport adapters while Foundgine centralizes semantic modeling, lexical grounding, warrant verification, and row-level authorization—executing through SQL or your existing EF Core / JPA persistence layer.
No. Foundgine is designed for conventional .NET 10 and Java 27 backend systems first. AI agents, MCP, GraphQL, and Temporal workflows are optional consumer adapters over the same configured semantic capabilities.
Caller input, capability discovery, retrieval scores, and model output are never treated as authority. Identity and tenant claims come strictly from host-verified tokens/warrants, ambiguous phrases fail closed with RequiresClarification, and write execution requires a host-signed fgmcp1 approval bound to the exact plan fingerprint.
Both runtimes share the five-concern fluent model, identical structural SecurityResourceLimits, and shared JSON conformance suites (src/conformance/) validated in CI on every change.